Last Updated:

OOP Principles - Java | Examples

Within the framework of this approach, the following terms are distinguished: abstractionencapsulationinheritance and polymorphism. Understanding these principles is key to building a holistic picture of how programs written in Java work. By and large, the object-oriented approach allows us to describe classes, define methods and variables in such a way that we can then use them again, partially or completely, without compromising security.
 

OOP Principles in Java

 
As mentioned above, there are four main principles of OOP:
  • Abstraction. Abstraction means using simple things to describe something complex. For example, we all know how to use TV, but at the same time we don't need to have knowledge of how it works to watch it. In Java, abstraction refers to things like objectsclasses, and variables, which in turn underlie more complex code. Using this principle allows you to avoid complexity in software development.
  • Encapsulation. Encapsulation refers to hiding fields within an object in order to protect data from external, uncontrolled change by other objects. Access to data (fields) is provided through public methods (getters/setters). This protective barrier allows you to keep information safe inside the object.
  • Inheritance. This is a special feature in object-oriented programming languages that allows you to describe new classes based on existing ones. This makes the fields and methods of the ancestor class available to the descendant classes. This feature makes classes cleaner and more understandable by eliminating duplication of program code.
  • Polymorphism. This principle allows programmers to use the same terms to describe different context-specific behaviors. One form of polymorphism in Java is method override, where different behaviors are defined by the object from which the method was invoked. Another form of polymorphism is method overloading, where its behavior is determined by a set of arguments passed to the method.
 

How OOP concepts work in Java

 
OOP concepts in Java allow programmers to create components that can be reused in different parts of a program without putting the data at risk.
 

How Abstraction Works

 
The main purpose of using this concept is to reduce the complexity of the components of the program by hiding unnecessary details from the programmer using these components. This allows you to implement more complex logic on top of the provided abstraction without going into the details of its implementation.

Making coffee with a coffee machine is a good example of abstraction. All we need to know is how to pour water, fill in coffee beans, turn on and choose the type of coffee we want to get. And, how the machine will brew coffee - we do not need to know.

In this example, the coffee machine is an abstraction that hides all the details of coffee brewing from us. We just have to interact with a simple interface that does not require us to know any about the internal implementation of the machine.

The same approach can be used in object-oriented programming languages such as Java.
 

How encapsulation works

 
Encapsulation allows us to take advantage of the class's capabilities without compromising data security by restricting direct access to its fields. It also allows you to modify the code of classes without creating problems for their users (other classes). In Java, this principle is achieved through the use of the private keyword.
 

How inheritance works

 
Inheritance is another important OOP concept that saves time on writing code. The possibilities of inheritance are revealed in the fact that the properties and methods of the class already described earlier are passed to the new class. The class that is inherited is called a child (or subclass). The class from which the new class is inherited is called the parent, ancestor, etc. The Java programming language uses the extends keyword to point to the ancestor class.
 

How polymorphism works

 
Polymorphism provides the ability to uniformly process objects with different implementations, provided that they have a common interface or class. Simply put: the ability to call the desired methods on objects that have different types (but are in the same hierarchy). This automatically selects the desired method depending on the type of object.

Let's look at examples of polymorphism in Java: overriding and overloading methods.

In the case of a method override, the child class, using the concept of polymorphism, can change (override) the behavior of the method of the parent class. This allows the programmer to use the same method differently, defining the behavior from the context of the call (a method is called from an ancestor class or an inheritor class).

In the case of overloading, the method can exhibit different behavior depending on what arguments it accepts. In this case, the context of the call is determined by a set of method parameters.
 

Examples of OOP concepts in Java

 
Let's look at a few common examples.
 

Encapsulation Example

 
The following example discusses one of the principles of OOP: encapsulation. The name field of the Student class is hidden from external code. To access this field, the getName() and setName(String name) methods are defined.
package com.p-qc;

public class Student {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name
    }
}
package com.p-qc;

class Test {

    public static void main(String[] args) {
        Student student = new Student();
        student.setName("Josh");
        System.out.println(student.getName());
    }
}
To compile, go to the root directory and run the command:
   javac -d out/com/p-qc/*.java

To run the program, run the command:
   java -cp out/ en.p-qc.Test

Conclusion:
     Josh
Example of using inheritance
In order to use the inheritance mechanism, you must use the extends keyword.
package com.p-qc;

public class Animal {

    //...
}
package com.p-qc;

public class Dog extends Animal {

    //...
}

Example of using polymorphism

 
To demonstrate polymorphism in Java, below are two classes, Person and Employee. The Employee class inherits from the Person class by using the extends keyword. Next, the Employee inherit class overrides the behavior of the walk() method of the Person class.
package com.p-qc;

class Person {

    void walk() {
        System.out.println("Can Run....");
    }
}
package com.p-qc;

class Employee extends Person {

    void walk() {
        System.out.println("Running Fast...");
    }


    public static void main(String[] arg) {
        Person p = new Employee();
        p.walk();
    }
}

Tips for Writing Good Code in the Java Programming Language

 
Ever since the principles of object-oriented programming were adopted by many languages, and to this day helping to organize a clear and well-maintained application architecture, many practices have appeared, compliance with which contributes to saving the programmer's time:
  • DRY (Don't Repeat Yourself). This is one of the fundamental principles of software development in Java. The essence of this rule is to avoid the appearance of the same code in different parts of the program. This is achieved by putting duplicate lines of code in the methods.

  • If you plan to make changes to the program in the future, then encapsulate the code as much as possible, making all its fields and methods private. As your app changes, extend access to protected as needed, but don't abuse public.

  • Single Responsibility. Another important principle, which should not be neglected. Its essence is that each class should have only one purpose. The responsibility of the class should lie solely in the field of its functionality.

  • Open Closed Design. Make all methods and classes private to modification but open to extension.
We will look at each of the principles of object-oriented programming in more detail in the next articles.