Java OOPs – What is Object Oriented Programming?

By | February 9, 2023

The Object Oriented Programming is a paradigm for designing programs using classes and objects. OOPs simplify and speed up software development and maintenance using concepts such as Object, Classes, Inheritance, Polymorphism, Abstraction and Encapsulation.

Object in Java

An object is a real-world, run-time entity. It has a state and a behavior. For example, A dog is an object, it has states such as name, color, weight, height etc. and along with this it has behavior such as eat, run, bark etc.

Object represents an instance of a class. An Object can operate on both data member and the member function of the class.

Note: In above example, the Dog itself is a class while the instance of Dog class represents an Object.

To learn more about Object please refer The Object Class.

Classes in Java

Classes are user-defined data types which define the object’s properties and functionalities. The classes are the blueprints for creating objects. The class does not occupy any space in the memory until an object of that class is instantiated.

Object Oriented Programming - Class
Fig 1 – Class definition

For example, In above picture, we have Dog class and it is having stats and behavior. We can create it’s object as following:

Java
//initializing dog object
Dog dog_obj = new Dog();
How Java Objects Stored In Memory
Fig 2 – Java objects stored in memory

Above, we can see how the objects are stored inside the memory in java. Stack memory is used to store the reference variable, local variables and function calls, while heap memory stores class variables and the objects.

Inheritance in Java

Inheritance
Fig 3 – Inheritance

It is the process in which one object inherits all the properties and behaviors of other object. The object which inherits the properties and behaviors are called child object and from which object it inherits are called parent object. Hence, inheritance involve two different classes the child classes and the parent classes.

In inheritance, when a child class inherits properties and behavior from parent class, it established the relationship between child and parent class know as Is-A relationship. For example, if we have a Dog class which inherits properties and behaviors from Animal class. We can say Dog Is-A Animal But, the reverse is not true .i.e., Animal Is-A Dog is not true for every animal.

Java
//we can achieve inheritance using extend keyword
public class Dog extends Animal {
	
	//Dog is an Animal But the vice-versa is not true
}
Note: Inheritance is used to achieve run time polymorphism.

Types Of Inheritance in Java

In Java, we have 3 different type of inheritance which are supported by class.

  • Single Level Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
Note: Multiple and Hybrid inheritance is not supported with class in Java. They can be achieved with the help of interfaces.

1. Single level inheritance in Java

It is also known as simple inheritance. In single level inheritance child class inherits the properties and behaviors from single parent class.

Single Level Inheritance
Fig 4 – Single level inheritance

In above figure, we can see Dog class inherit the name(String name)

Java
/*Single level inheritance*/
//parent class
class Animal{
  //return name of the animal
  public String name(String name) {
      return name;
  }
   
}
//child class extends parent class
public class Dog extends Animal{
  //return sound of the dog
  public void bark() {
      System.out.print("Bark..Bark..");
  }
  public static void main(String[] args) {
      //the Dog class inherits the behavior of the Animal class
      Dog dog = new Dog();
      System.out.print(dog.name("Dog ") );
      dog.bark();
  }
}

Output:

Fig 5 – Output

2. Multilevel inheritance in Java

In multi-level inheritance, first class inherits properties and behaviors from second class and the second class inherits from some other class. It form a chin of inheritance.

Multi-Level Inheritance
Fig 6 – Multi-level inheritance
Java
/*Multi-level inheritance*/
class Animal{
	public String name(String name) {
		return name;
	}
}
class Dog extends Animal{
	//Dog class inherit the name() method of Animal class
	public void bark() {
		System.out.println("Bark..Bark..");
	}
}
public class Puppy extends Dog{
	public void wiggle() {
		System.out.println("wiggle tail..");
	}
	public static void main(String[] args) {
		//Puppy class inherit the name() method form Animal class
		//and bark() method form Dog class
		Puppy puppy = new Puppy();
		System.out.print(puppy.name("Puppy "));
		puppy.bark();
		puppy.wiggle();
	}
}

Output:

Fig 7 – Output

3. Hierarchical inheritance in Java

In hierarchical inheritance, two or more classes inherits properties and behaviors from a single class.

Hierarchical Inheritance
Fig 8 – Hierarchical inheritance
Java
/*Hierarchical inheritance*/
class Animal{
	public String name(String name) {
		return name;
	}
}
class Dog extends Animal{
	//Dog class inherit the name() method of Animal class
	public void bark() {
		System.out.println("Bark..Bark..");
	}
}
class Cat extends Animal{
	//Cat class inherit the name() method of Animal class
	public void meow() {
		System.out.print("Meow..Meow..");
	}
}
public class Test {
	public static void main(String[] args) {
		Dog dog = new Dog();
		//passing name as "Dog"
		System.out.print(dog.name("Dog "));
		dog.bark();
		
		System.out.println("-----------------");
		
		//passing name as "Cat"
		Cat cat = new Cat();
		System.out.print(cat.name("Cat "));
		cat.meow();
	}
}

Output:

Fig 9 – Output

Rules for inheritance

  • Why inheritance
    • Inheritance is used to increase the code reuse-ability and read-ability.
  • Constructor inheritance
    • A child class can inherit all the data members(fields, methods and nested classes) from it’s parent class. Constructors are not members of class, they are used to initialize the object of the class. So, we can not inherit constructors.
    • Constructors of parent class can be invoked. In Java, constructors get executed because of the super() method class.
  • Parent class can be only one
    • A parent class can have any number of child classes but, a child class can have only one parent class. Because of this, In java, multiple inheritance is not supported.
  • Private member inheritance
    • A child class can not inherit private members of parent class. However, If parent class have public or protected methods such as getters and setters for accessing private members. They can be accessed in child class also.

Polymorphism in Java

The word Polymorphism is comprises of two different words ‘poly’ which means ‘many’ and ‘morphs’ which means ‘form’. Polymorphism is the ability to present same entity with different forms. For example: A man can be a father, son or husband at the same time.

Types Of Polymorphism in Java

In Java, we can achieve polymorphism using two different ways.

  • Method Overloading(Compile-time Polymorphism)
  • Method Overriding(Run-time Polymorphism)

1. Method Overloading in Java

Methods with same name but different signature is called method overloading.

It is also know as compile-time polymorphism because of which it is implemented at compile time. In method overloading we overload a method by changing the number of arguments or by changing the type of arguments passed to a method.

Polymorphism - Method Overloading
Fig 10 – Method overloading

In Animal class, we are overloading the animalInfo() method with the number of arguments passed to it and the type of arguments passed to it.

Java
/*Method Overloading - Compile Time Polymorphism*/
public class Animal {
	
	//method definition
	public void animalInfo(String animalName) {
		System.out.println(animalName);
	}
	
	//overloading with type of argument
	public void animalInfo(int animalWeight) {
		System.out.println(animalWeight + "Kg");
	}
	
	//overloading with number of arguments
	public void animalInfo(String animalName, int animalWeight) {
		System.out.println(animalName + " " + animalWeight + "Kg");
	}
	
	public static void main(String[] args) {
		Animal animal = new Animal();
		animal.animalInfo("Dog");
		animal.animalInfo(20);
		animal.animalInfo("Dog", 20);
	}
}

Output:

Fig 11 – Output

Rules for overloading

  • Why overloading
    • It will increase the code reuse-ability. We do not have to create and remember the methods doing same functionality.
  • Constructor overloading in Java
    • We can overload constructor. In Java, we have default and parametrized constructor.
  • Overload a method on the basis of return type
    • We can not overload a method on the basis of return type of the method. It will generate compile-time error.
Java
/*Method overloading on the basis of return type of method*/
public class Test {
	
	public int fun() {
		return 100;
	}
	
	//overloading a method on the basis of return type
	//generate compile-time error
	public String fun() {
		return "paulsofts";
	}
}

Output: Generate compile-time error

Polymorphism - Method Overloading
Fig 12 – Overloading on the basis of return type of method
  • Can we overload static method in Java
    • Static method can be overloaded(method signature should be different).
  • Can we overload a method which differ only be static keyword
    • No, we can not overload a static method which differ only by static keyword. If we do so, it will generate compile-time error.
Java
/*Method overloading on the basis of return type of method*/
public class Test {
	
	public static int fun() {
		return 100;
	}
	
	//method overloading which differ only by static keyword
	//generate compile-time error
	public int fun() {
		return 200;
	}
}

Output: Generate compile-time error

Fig 13 – Method overloading differ only by static keyword
  • Can we overload main method in Java
    • As main method is a static method, we can overload main method as other static methods.
Java
/*Main method overloading*/
public class Test {
	
	public static void main(String agr1) {
		System.out.println("Paulsofts");
	}
	
	public static void main(String agr1, String arg2) {
		System.out.println("Easy learnings");
	}
	
	public static void main(char ch) {
		System.out.println(ch);
	}
	
	public static void main(String[] args) {
		
		Test test = new Test();
		//calls main method which takes two String argument
		test.main("one", "two");
		//calls main method which takes one char argument
		test.main('@');
		//calls main method which takes only String argument
		test.main("one");
	}	
}

Output:

Fig 14 – Output
  • Can we overload final method in Java
    • Yes, we can overload final method.
Java
/*final method overloading*/
public class Test {
	
	public final void fun(String str) {
		System.out.println(str);
	}
	
	public final void fun(String str1, String str2) {
		System.out.println(str1 + " " + str2);;
	}
	
	public static void main(String[] args) {
		Test test = new Test();
		test.fun("Paulsofts");
		test.fun("Easy", "Learnings");
	}	
}

Output:

Fig 15 – Output
  • Operator overloading in Java
    • Java does not support user defined operator overloading like C++.
    • Implicitly Java overloads the operator. For example: “+” operator is overloaded for concatenation in Java.

2. Method Overriding in Java

Methods with same name, same signature and return type.

It is also known as run-time polymorphism as which method is going to be called is determined at run-time. In method overriding a child class method provide a specific implementation to a parent class method.

Polymorphism - Method Overriding
Fig 16 – Method overriding

In Dog class, we are overriding the animalInfo() and animalSound() methods and we will provide our own implementation according to the Dog class requirement.

Java
/*Method Overriding*/
class Animal {
	
	public void animalInfo() {
		System.out.println("This is an animal");
	}
	
	public void animalSound() {
		System.out.println("All animals make sounds");
	}
}
public class Dog extends Animal{
	//Dog is child class of Animal
	//Dog class provide specific implementation according to own requirement
	@Override
	public void animalInfo() {
		System.out.println("Dog is an animal and is man's best friend");
	}
	@Override
	public void animalSound() {
		System.out.println("Dog barks and wiggle tail");
	}
	
	public static void main(String[] args) {
		Dog dog = new Dog();
		dog.animalInfo();
		dog.animalSound();
	}
}

Output:

Fig 17 – Output
Note: In overriding, which method is going to be invoked, parent class method or child class method is determined at run-time by the type of object which is used to invoke the method. If the parent class object is used to invoke the method then parent class method definition is executed otherwise if child class object invoke the method then child class method definition(overriding definition) will be executed. In below example, we have used reference variable of parent class is used but which method definition is going to executed is determined by the object type.
Java
/*Method Overriding*/
class Animal {
	
	public void animalInfo() {
		System.out.println("This is an animal");
	}
	
	public void animalSound() {
		System.out.println("All animals make sounds");
	}
}
public class Dog extends Animal{
	//Dog is child class of Animal
	//Dog class provide specific implementation according to own requirement
	@Override
	public void animalInfo() {
		System.out.println("Dog is an animal and is man's best friend");
	}
	@Override
	public void animalSound() {
		System.out.println("Dog barks and wiggle tail");
	}
	
	public static void main(String[] args) {
		
		//Object type of parent class
		Animal animal1 = new Animal();
		animal1.animalInfo();
		animal1.animalSound();
		
		System.out.println("------------------------");
		
		//Object type of child class
		Animal animal2 = new Dog();
		animal2.animalInfo();
		animal2.animalSound();
	}
}

Output:

Fig 18 – Output

Rules for overriding

  • Why overriding
    • It used used to write generic code based on the parent class method definition.
  • Constructor overriding in Java
    • We can not override a constructor. It is because parent and child class can not have same construct or same class name.
  • Can we override static method in Java
    • We can not override static method as method overriding is based on dynamic binding at run-time while static methods uses static binding at compile-time.
    • If we override static method and provide same name and same signature of parent class method in child class, this is called Method hiding.
    • Static methods are class level method which means same method definition shared among all the objects and no object can change it’s definition.
  • Can we override final method in Java
    • No, we can not override a final method. If we do so, compiler will throw a compile time exception.
    • We make a method final if we do not want it to be overridden.
  • Can we override private method in Java
    • Private method binding happens at compile time while overriding is a run-time operation. So, we can not override a private method.
  • Access modifier in Java
    • In overriding, the access modifier of a method in parent class can have more access in child class but not less access. For example:
      • Method declared as public in parent class must be declared as public in child class.
      • Method declared as protected in parent class can be protected or public in child class but not private.
      • Method declared as private can not be overridden.
      • Access modifier access scope increasing order
Access Modifier
Fig 19 – Access modifier for method overriding

Abstraction in Java

Abstraction is the process of hiding the implementation details and showing only necessary details to the end user. For example: Google Pay App, the end used don’t need to know the internal implementation how the payment gateway is working. They just need to enter the amount and the password to complete the payment.

In Java, abstraction can be achieved by using:

  • Abstract Class
  • Interface(complete 100% abstraction)

1. Abstract Class in Java

  • Abstract class must be declared with the help of abstract keyword.
  • Abstract class can have abstract(method with declaration only, not definition) as well as non-abstract methods(method with body).
  • We can not create object of abstract class.
  • Abstract class can have constructor.
  • Abstract class can have static method.
  • Abstract class can have final method.
Abstraction In Object Oriented Programming
Fig 20 – Object Oriented Programming – Abstraction
Java
/*Abstraction using abstract class*/
abstract class Animal {
	Animal(){
		System.out.println("Animal created");
	}
	
	//abstract method
	abstract void animalInfo();
	abstract void animalWalk();
	
	//non-abstract method
	public void animalBreath() {
		System.out.println("This animal breath oxygen");
	}
}
public class Dog extends Animal{
	
	Dog(){
		System.out.println("Dog created");
	}
	@Override
	void animalInfo() {
		System.out.println("This animal is a Dog");
		
	}
	@Override
	void animalWalk() {
		System.out.println("Dog walks on 4 legs");
		
	}
	
	public static void main(String[] args) {
		Dog dog = new Dog();
		dog.animalInfo();
		dog.animalWalk();
		dog.animalBreath();
	}
	
}

Output:

Fig 21 – Output

2. Interface in Java

  • Interface is used to achieve 100 % abstraction. In interface we have method declaration only and the implementation for every method is provided by the implementing class.
  • All the fields in an interface are by default public, static and final.
  • All the methods in an interface are by default public and abstract.
  • We can not create object of interface.
  • Interface can be used to achieve multiple inheritance.
Interface
Fig 22 – Interface
Java
/*Abstraction using interface*/
interface Animal{
	//all the methods are by default public and abstract
	public void animalInfo();
	public void animalWalk();
	public void animalBreath();
}
public class Dog implements Animal{
	@Override
	public void animalInfo() {
		System.out.println("This animal is a Dog");
	}
	@Override
	public void animalWalk() {
		System.out.println("Dog walks on 4 legs");
	}
	@Override
	public void animalBreath() {
		System.out.println("Dog breath oxygen");
	}
	
	public static void main(String[] args) {
		Dog dog = new Dog();
		dog.animalInfo();
		dog.animalWalk();
		dog.animalBreath();
	}
}

Output:

Fig 23 – Output

Encapsulation in Java

Encapsulation In Object Oriented Programming
Fig 24 – Object Oriented Programming – Encapsulation

The process of wrapping up of data and the methods which operate on that data into a single unit is called encapsulation.

For Example: Defining a class is also an example of encapsulation, we declare the data(fields and variables) and the method which operate on that data(gettera, setters and user-defined methods).

Rules for encapsulation

  • Why encapsulation
    • Encapsulation is used to increase the flexibility of application programs. It will help us in making our variables as read-only or write-only.
    • Make variable read-only : omits the setter methods
    • Make variable write-only : omits the getter methods
  • Data hiding
    • In order to achieve encapsulation, we need to define the variables as private and need to provide public getters and setters method to get and set the values to those variables. As we hide the data(by making variables private) encapsulation also referred as Data hiding.
Encapsulation
Fig 25 – Class Diagram for Encapsulation
Java
/*Encapsulation*/
public class Animal {
	
	private int animalAge;
	private String animalName;
	
	//default constructor
	public Animal() {
		
	}
	
	//all args constructor
	public Animal(int animalAge, String animalName) {
		super();
		this.animalAge = animalAge;
		this.animalName = animalName;
	}
	
	//getters
	public int getAnimalAge() {
		return animalAge;
	}
	public void setAnimalAge(int animalAge) {
		this.animalAge = animalAge;
	}
	
	//setters
	public String getAnimalName() {
		return animalName;
	}
	public void setAnimalName(String animalName) {
		this.animalName = animalName;
	}
	
	public static void main(String[] args) {
		Animal animal = new Animal();
		//setting animal fields
		animal.setAnimalAge(2);
		animal.setAnimalName("Dog");
		//getting animal fields
		System.out.println(animal.getAnimalName() + " - " + animal.getAnimalAge() + "y ears old");
	}
}

Output:

Fig 26 – Output

One thought on “Java OOPs – What is Object Oriented Programming?

  1. Sahil Awasthi

    Great blog post! I really appreciate the clear and concise explanation of OOP concepts. Your examples really helped me understand the importance of encapsulation and inheritance in software design. I especially liked how you broke down the real-life scenario to make the abstract concepts more relatable. Thank you for taking the time to write this informative article.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *