Java OOPs Concepts – Object Oriented Programming in Java

We all know that Java programming language is an Object-Oriented Language. The main objective of the object-oriented paradigm is to implement real-world entities, like, Objects, Classes, Abstraction, Inheritance, Polymorphism, etc.

In this article, we will learn Java as an Object-Oriented language along with its concepts and examples. We will cover every feature of OOPs in detail so that you will not face any difficulty understanding Java OOPs Concepts.

Java OOPs

What Is Object-Oriented Programming(OOP)?

Object-Oriented Programming refers to programming that helps us to create the objects that we want and create methods to handle these objects. The principle of OOP is to create objects, reuse the objects throughout the program, and manipulate these objects to get desired outputs.

The primary objective of object-oriented programming is to enhance the maintainability and flexibility of applications. Object-oriented programming brings together data, and its behavior (methods) in a single location(object) makes it easier to understand how a program works.

Benefits of Object-Oriented Programming

  • Improved productivity during software development
  • Improved software maintainability
  • Faster development sprints
  • Lower cost of development
  • Higher quality software

Challenges associated with OOP

  • Steep learning curve
  • Larger program size
  • Slower program execution
  • It is not a one-size-fits-all solution

What is an Object?

java object

The object is a bundle of data and its behavior or methods. Objects have two characteristics: states and behaviors.

Examples of states and behaviors of an object:

Object: Student
State: name, age, gender
Behavior: study, play, run

So if we need to write a class based on states and behaviors of the Student. We can represent the states as instance variables and behaviors as methods of the class. Let’s see the example:

class Student {
  //States as instance variables
  String name;
  String gender;
  int age;

  //Behavior as methods
  void study() {
    //Write code here
  }
  void play() {
    //Write code here
  }
  void run() {
    //code
  }
}

Message passing

A single object may not be beneficial by itself. An application can have many objects. One object communicates with another object by invoking methods or functions on that object. This process is called Message Passing. Below figure shows the message passing process in Java:

Java Message Passing

What is Class in OOPs Concepts?

A class is a blueprint that creates as many objects as we need. For example, we have a class Website that has two data members or fields or instance variables. This class is just a blueprint or a template. It does not represent any real website.

But, using this class, we can create objects or instances of Website class that represent the websites. We created two objects in the below program. And, while creating objects we provided separate properties to the objects using a constructor.

package com.techvidvan.javaoops;
public class Website {
  //fields (or instance variable)
  String websiteName;
  int websiteAge;

  //constructor
  Website(String name, int age) {
    this.websiteName = name;
    this.websiteAge = age;
  }
  public static void main(String args[]) {
    //Creating objects
    Website obj1 = new Website("Techvidvan", 2);
    Website obj2 = new Website("Google", 18);

    //Accessing object data through reference
    System.out.println(“Website Name: “ + obj1.websiteName);
    System.out.println(“age: “ + obj1.websiteAge)
    System.out.println(“Website Name: “ + obj2.websiteName);
    System.out.println(“age: “ + obj2.websiteAge)
  }
}

Output:

Website Name: Techvidvan
age: 2
Website Name: Google
age: 18

What is Method in OOP?

A method in Java is a collection of statements that perform some specific task. The method returns the result of the statements inside it. A method can also perform some specific task without returning anything.

Methods enable users to reuse the code without typing the code again. In Java, every method must belong to some class. We declare a method in Java as:

accessSpecifier returnType methodName(argument-list)

For example:

public int addNumbers(int num1, int num2)

Java OOPs Concepts

After having an overview of Object-Oriented programming, let’s learn the concepts of OOPs.

OOPs Concept in Java

These are:

1. Abstraction in Java

Abstraction is a process to represent only “relevant” or essential data and “hide” the unnecessary or background details of an object from the user.

Let us take an example to understand abstraction. Suppose, You are driving a car. While driving, you only know the essential features of a car, such as gear handling, steering handling, use of the clutch, accelerator, brakes, etc. But while driving, do you get into the car’s internal details like wiring, motor working, etc.?

You just change the gears or apply the brakes, etc. What is happening inside the car is hidden from you. This is an abstraction where you only know the essential things to drive a car without including the background details or explanations.

Take another example of ‘switchboard’. You only press individual switches according to your requirement. What is happening inside, how it is happening, etc. You need not know. Again this is an abstraction; you know only the essential things to operate on the switchboard.

We can achieve abstraction in two ways:
a) Abstract Class
b) Interface

Let’s understand these concepts in more detail.

a. Abstract class

An Abstract class in Java uses the ‘abstract’ keyword. If we declare a class as abstract, we cannot instantiate it, which means we cannot create an abstract class object. Also, In an abstract class, there can be abstract as well as concrete methods.

We can achieve 0-100% abstraction using abstract class.

Let us look at the syntax of an abstract class:

abstract class Person //abstract class
{
  abstract void talk(); //abstract method
  void walk() //non-abstract method
  {
    //code of method
  }
}
b. Interface

Interface is a blueprint of a class. An interface is a collection of abstract methods and static constants. Each method in an interface is public and abstract, but there is no constructor. Interfaces also help to achieve multiple inheritance in Java.

We can achieve 100% abstraction using interfaces.

public interface Car {
  //abstract methods
  abstract void run();
  Abstract void initSpeed();
}

2. Encapsulation in Java

Encapsulation is a way of combining both data members and functions/methods into a single unit. In Encapsulation, we keep the fields within a class as private, and then we provide access to them using public getter and setter methods.

Encapsulation is a kind of protective barrier that keeps the data and methods safe within the class itself. Using Encapsulation, we can reuse the code components or variables without allowing open access to the data.

We can implement Encapsulation in two ways:

1. Declare the instance variables as private. We make them private, so no one from outside the class can access them directly. We can only set and get the values of these variables using the methods of the class.

2. Provide the getter and setter methods in the class. These methods set and get the values of the instance variables.

Now, let us see an example if Encapsulation in Java:

package com.techvidvan.javaoops;
class EmployeeCount {
  private int numOfEmployees = 0;
  public void setNoOfEmployees(int count) {
    numOfEmployees = count;
  }
  public int getNoOfEmployees() {
    return numOfEmployees;
  }
}
public class EncapsulationDemo {
  public static void main(String args[]) {
    EmployeeCount obj = new EmployeeCount();
    obj.setNoOfEmployees(3593);
    System.out.println(" The number of Employees are : “ + obj.getNoOfEmployees());
    	}
}
"

Output:

The number of Employees are: 3593

The class EncapsulationDemo uses the object of EmployeeCount class. It will not be able to get the NoOfEmployees directly. We need to use the setter and getter methods of the same class to set and get the value.

The benefit of Encapsulation in Java programming:
Whenever we need to change the class’s implementation details, we can freely do so using Encapsulation, without affecting the classes that are using it.

3. Inheritance in Java

Inheritance is a feature of Object-Oriented Programming in Java that allows programmers to create new(child) classes that share some of the attributes of existing(parent) classes. It is an object-oriented process by which one class acquires or inherits the properties and functionalities of another class.

Inheritance provides the reusability of code. Each child class defines only those features that are unique to it, and the child class inherits the rest of the features from the parent class.

The most significant advantage of Inheritance is that we need not rewrite the base class’s code in the child class. We can use the variables and methods of the base class in the child class as well.

Syntax of Inheritance in Java

To inherit a class we use the ‘extends’ keyword. Here class A is the child class, and class B is the parent class.

class A extends B
{
  //code
}

Example of Inheritance

package com.techvidvan.javaoops;
class Teacher {
  String designation = "Teacher";
  String school = "Techvidvan";
  public void teach() {
    System.out.println("Teaching");
  }
}
public class JavaTeacher extends Teacher {
  String mainSubject = "Java";
  public static void main(String args[]) {
    JavaTeacher obj = new JavaTeacher();
    System.out.println(obj.school);
    System.out.println(obj.designation);
    System.out.println(obj.mainSubject);
    obj.teach();
  }
}

Output:

Techvidvan
Teacher
Java
Teaching

Types of Inheritance in Java

1. Single Inheritance: Single Inheritance is a child and parent class relationship where one class extends another class.

2. Multilevel Inheritance: Multilevel Inheritance is a child-parent relationship when a class extends the child class, and that child class becomes a parent class for another class, and so on. For example, class A extends class B, and class C extends class B.

3. Hierarchical Inheritance: Hierarchical Inheritance refers to a child-parent class relationship where more than one class can extend the same parent class. For example, class B extends class A, and class C extends class A.

4. Multiple Inheritance: Multiple Inheritance refers to a parent-child class relationship when one child class extends more than one parent class. This means, a child class can have more than one parent class. Java does not support multiple inheritance using classes, but with interfaces.

4. Polymorphism in Java

This Java OOPs concept lets programmers use the same word to mean different things in different contexts. One form of Polymorphism in Java is method overloading. That’s when the code itself implies different meanings. The other form is method overriding.

Polymorphism is an object-oriented programming feature that allows us to perform a single action in different ways.

Java program to demonstrate Polymorphism

package com.techvidvan.javaoops;
//This class has three methods with the same name.
public class PolymorphismDemo {
  //Overloaded sum method(). 
  //This sum takes two int parameters 
  public int sum(int num1, int num2) {
    return (num1 + num2);
  }

  //Overloaded sum() method. 
  //This sum takes three int parameters 
  public int sum(int num1, int num2, int num3) {
    return (num1 + num2 + num3);
  }

  //Overloaded sum() method.
  //This sum takes two double parameters 
  public double sum(double num1, double num2) {
    return (num1 + num2);
  }

  public static void main(String args[]) {
    PolymorphismDemo obj = new PolymorphismDemo();
    System.out.println(obj.sum(10, 20));
    System.out.println(obj.sum(10, 20, 30));
    System.out.println(obj.sum(10.5, 20.5));
  }
}

Output:

30
60
31.0

Types of Polymorphism

a. Static Polymorphism
b. Dynamic Polymorphism

a. Static Polymorphism

Polymorphism that the compiler resolves during the compile-time is called the static polymorphism. We can consider Method overloading as a static polymorphism example in Java.

Method Overloading allows us to have more than one method with the same name in a class with a different signature. The above example of polymorphism is the example of method overloading or static polymorphism in Java.

b. Dynamic Polymorphism

The other name for Dynamic Polymorphism is Dynamic Method Dispatch. Dynamic or runtime polymorphism is a technique in which the overridden method is resolved at runtime rather than the compile-time. That’s why it is called runtime polymorphism.

Example of Runtime-polymorphism:

package com.techvidvan.javaoops;
class Animal {
  public void makeSound() {
    System.out.println("Default Sound");
  }
}
public class Dog extends Animal {@Override
  public void makeSound() {
    System.out.println("Bark");
  }
  public static void main(String args[]) {
    Animal obj = new Dog();
    obj.makeSound();
  }
}

Output:

Bark

Since both child class and parent class have the same method makeSound(), JVM determines which methods to call at runtime.

Association

Association is an OOPS concept that defines the relationship between objects. The association represents the multiplicity between objects. For example, there are two objects: Teacher and Student. There exists a ‘one-to-many’ relationship between a teacher and students.

There can be one teacher for many students, and there can be many teachers for a single student. However, both teacher and student objects are independent of each other.

Aggregation

Aggregation is a special type of Association in Java. It represents a has-a relationship between two objects(object and their owner). Objects have their own life cycle but they have an ownership.

Composition

Composition in Java is a special case of Aggregation. It is more restricted than Aggregation. When the contained object that represents a “HAS-A” relationship is unable to exist on its own, then it is a case of Composition.

For example, House and Room. Here, the room can not exist without the house. Similarly, Library and books, If we delete the library, the books will be deleted automatically.

Coupling

Coupling in Java refers to the information or dependency of one class on another class. It occurs when classes are aware of each other or interact with each other. If a class contains detailed information about another class, then we say that there is strong coupling between them.

We can use interfaces to have weaker coupling between classes because there is no concrete implementation in interfaces.

Cohesion

Cohesion refers to the level of performing a single well-defined task by a component. A highly cohesive method performs a single well-defined task. While, the weakly cohesive method will split the task into different parts.

The java.io package is a highly cohesive package in Java because this package contains the classes and interfaces related to I/O(Input/Output). The java.util package is considered as a weakly cohesive package because there are unrelated classes and interfaces in it.

Advantages of OOPs over Procedure-oriented programming language

1. It is easy to develop and maintain the code with Object Oriented Programing. whereas,, it is not easy to manage the code in a procedure-oriented programming language if code grows with the size of the project..

2. Object Oriented Programming provides data hiding, whereas, in a procedure-oriented programming language, we can access global data from anywhere.

3. Object Oriented Programming provides the ability to simulate real-world events much effectively as compared to Procedural Oriented programming. We can easily solve the real world problems if we are using the Object-Oriented Programming language.

Best Practices for OOP Concepts in Java

The objective of OOP concepts in Java is to save time and gain security and ease of use. We should follow the best practices towards advancing that primary goal of OOPs. The best practices while using OOPs concepts in Java are:

1. DRY (Don’t Repeat Yourself): You should never try to have two blocks of identical/same code in two different places of the program or application. Instead, we should use one method for various applications.

2. Encapsulate methods and variables using private: If you expect that your Java code can change in the future, you should encapsulate it by making all variables and methods private. As there are some changes in the code, you can increase the access to “protected” as needed, but do not use public.

3. Single Responsibility Principle: This is another best practice for OOP concepts in Java. This principle says that a class should always have only one functionality. That way, we can call it or extend it on its own whenever new uses arise without providing coupling between different functionalities.

4. Open Closed Design: We should try to make all the methods and classes Closed for any modification but open for an extension. That way, the tested code can remain static, but we can modify it to perform new tasks as required.

Conclusion

We hope you guys are clear with all the object-oriented programming concepts in Java. We have discussed the java OOPs concepts like Inheritance, Encapsulation, Abstraction, and Polymorphism.

Using these OOPs concepts in java, you can easily make your Java application more secure, simple, and reusable.

Do share your feedback in the comment section if you liked the Java Tutorial.