Last Updated:

Object-Oriented Programming in Java with Sample Code

Table of Contents

What is an object?

Object is the key to understanding object-oriented technology. Right now look around and you will see many examples of real world objects: your dog, your desk, TV, bicycle.

Real-world objects are endowed with two characteristics: state and behavior. The dog has a "condition" (name, suit, coat, appetite) and behavior (barking, wagging its tail). The bike also has a state (current gear, current speed) and behavior (change of gear, change of speed). To start thinking in terms of object-oriented programming, you need to highlight the state and behavior of the object. Right now, take a couple of minutes to look at the real-world objects that are around you. For each object that you see, answer the questions: "What possible states can this object take?", "What actions can this object perform?". Write down your observations. You've probably noticed that objects vary in complexity; Your desk lamp has two possible states (on and off) and two possible actions (on, off), but the desktop radio can have the following set of states: on, off, current volume, current station; and possible actions: turn on, off, increase volume, decrease volume, search, station, etc. In addition, you may notice that some objects contain other objects. All of these real-world objects can be translated into object-oriented programming objects.

Fundamentally, software objects do not differ from real-world objects: they are all described by state and behavior. An object stores its state in fields (variables in some programming languages) and implements its behavior through methods (functions in some programming languages). Methods operate with the internal state of the object and are considered as the main mechanism of object-oriented communication. Hiding the inner state and requiring you to work with it exclusively through methods is called encapsulation. Encapsulation is a fundamental principle of object-oriented programming.

Take a bicycle as an example.

Through the attributes of the state (current rate, current transfer) and methods of changing this state, the object stores the correctness of its state and shows how it can be used. For example, if a bike has only six gears, the gear change method will not accept values that are less than one and greater than six.

Hiding code inside an object has a number of advantages:

Modularity. The source code of an object can be written and modified independently of the code of other objects. Once created, the object can be arbitrarily used in the system.
Concealment of information. All interactions with the object are carried out by means of methods, while the details of the internal implementation are hidden from the outside world.

Code reuse. If the object already exists (possibly created by another developer), you can use it in your program. With this approach, you can use specific objects written and tested by narrow specialists.

Easy debugging and connectivity. If some object is unstable, you can simply remove it from the application and replace it with another. As an analogy, we can give an example from the real world. If you have a broken bolt, you change the broken bolt, not the entire mechanism.

What is a class?

In the real world, you often come across many objects of the same kind. For example, it can be thousands of bicycles of one production and one model. All bicycles are assembled according to one set of drawings and therefore consist of the same components. In object-oriented terms, we can say that your bike is an instance of a class of objects called bicycles. This class is the drawing from which specific objects are created.

The following is an example of a class, one of the possible implementations.

class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear); } } 

The syntax of the Java programming language will seem new to you, but the logic of the class is based on the previous discussion of bicycle objects. The cadence, speed, and gear fields are the state of an object, and methods (changeCadence, changeGear, speedUp, and so on) define interaction with the outside world.

You may have noticed that the Bicycle class does not contain a main method. And that's because it's not a finished app, it's just a drawing of the bikes that you can use in the app. the other classes in your application are responsible for using the new object

The following is an example of the BicycleDemo class, the class creates two separate Bicycle objects and calls their methods.

class BicycleDemo { public static void main(String[] args) { // Creating two Bicycle objects. Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); Calling the methods of these objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } } 

Here is the output of the current states of objects:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3

What is inheritance?

Many types of objects often have a lot in common. For example, mountain biking, road bike, tandem, all these objects have common cycling properties (current speed, pedal torsion rate, current transmission). However, these types of bicycles have differences: the tandem has two seats, two handlebars; The road bike has a modified handlebar, some mountain bikes have an additional lower gear chain gear.

Object-oriented programming allows classes to inherit the commonly used behavior and state of another class. For example, the Bike is a superclass for the Mountain Bike, Highway Bike and Tandem classes. In the Java programming language, each class can have only one superclass, but one superclass can have an unlimited number of descendants.

The syntax for creating a descendant class is similar to a type class. First, use the extends keyword to specify the name of the class from which you want to inherit.

class MountainBike extends Bicycle { //there will be new fields and methods defining the mountain Bike class. } 

Thus, the Mountain Bike has all the fields and methods of the Bicycle class, in addition, it contains specific features that make this class unique. This approach makes the child class easy to understand. However, you need to take care to properly document the state and behavior of the superclass, as this code will be part of all descendant classes.

What is the interface?


As you already know, the object determines its interaction with the outside world through public methods. Methods are the interface of an object with the outside world. For example, the buttons on the front of your TV are the interface between you and the electronic parts inside a plastic box. You press the "Power" button to turn the TV on or off.

In general, an interface is a group of related methods with empty bodies. Bicycle behavior defined as an interface can be represented as follows:

interface Bicycle { void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } 

To implement this interface, you must create your class with a different name (for example, ACMEBicycle), and in the class declaration you must use a special keyword.

class ACMEBicycle implements Bicycle { // the rest of the implementation of class } 

The implementation of the interface allows you to create more standardized classes, with more predictable behavior. An interface is a contract for interaction between a class and the outside world, and this contract is validated by the compiler at compile time of the class. To compile the file successfully, you must write the bodies for all the methods declared in the interface.

Note: To compile the ACMEBicycle class, you need to add the public keyword to the beginning of the interface methods.


What is a package?

A package is a namespace that contains related classes and interfaces. Conceptually, you can think of packages as different folders on your computer. You can store HTML pages in one folder, images in another, scripts and applications in a third. Since a Java application can consist of hundreds or thousands of individual classes, having a way to store related classes and interfaces in an orderly manner looks very attractive and logical.

The Java platform offers a huge library of classes (a set of packages) ready for use in your applications. This library is known as the Application Programming Interface or API. These packages perform the most common programming tasks. For example, a String object contains the state and behavior of character strings; the File object allows the programmer to easily perform operations (create, delete, rename, etc.) with the files of the operating system; The Socket object allows you to create and use network sockets. various GUI (graphical user interface) objects: buttons, chekboxes, etc. can be used to create a graphical interface. You can choose from literally thousands of classes. This will allow the developer to focus on creating application logic and not be distracted by the technical details of the implementation.

 The Java Platform API Specification ( contains a complete list of all the packages, interfaces, classes, fields, and methods that Java Platform 6, Standard Edition provides. It is difficult to overestimate the importance of this page for the programmer, make a bookmark on it in your browser. 

This article is based on the official documentation of Sun Microsystems, Inc.