• Articles
  • Tutorials
  • Interview Questions

Encapsulation in Java With Examples

Encapsulation in Java

There are three main features of the OOPs concept:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism

1. Encapsulation

Wrapping up data and methods into a single unit is known as encapsulation. It provides the security that keeps data and methods safe from unwanted changes. A class is an example of encapsulation that binds fields and members into a single unit.

Learn Java

To get encapsulation:

  • Declare the variables of a class as private
  • Provide public getter and setter methods to change and sight the variable’s values

 
Example

public class Addition{
private int sum;
public void settotal(int a, int b){
sum = a + b;
}
public void gettotal()
{
System.out.println("Addition of two numbers:" +sum );
}
public static void main(String []args){
Addition add = new Addition ();
add.settotal(10, 20);
add.gettotal();
}
}

2. Java Inheritance

Inheritance is the process in which one class acquires all the properties of another class. It comes under object-oriented programming.

Whenever a class inherits from an already existing class, the methods and fields of the parent class can be reused. Also, new methods and fields can be added to the present class. Inheritance signifies an IS-A parent-child relationship.

What is the need to use inheritance?

We use inheritance for the reusability of the code and to achieve runtime polymorphism.

The following are general terms used in inheritance: 

  • Class: It contains a group of objects with common properties.
  • Parent class or superclass: The parent class is the class from where a child class inherits the properties. We can also call it a base class.
  • Child class or subclass: A child class is a class that inherits properties from another class (the parent class). We can also call it a derived class, extended class, or a subclass.
  • Reusability: Inheritance helps us reuse the fields and methods of the existing class when we create a new class.

Syntax:

class Subclass-name extends Superclass-name
{
//methods and fields
}

Here, the ‘extends’ keyword signifies the making of a new class that derives from an already existing class. It increases the functionality.

Example of Java inheritance:

Java Inheritance

In the above image, ‘Software Engineer’ refers to the subclass, and ‘Employee’ refers to the superclass. The relationship between these two classes is ‘Software Engineer IS-A Employee,’ which means that Software Engineer is a type of an Employee.

class Employee{
float salary=50000;
}
class Software_Engineer extends Employee{
int bonus=8000;
public static void main(String args[]){
Software_Engineer s=new Software_Engineer();
System.out.println("Software_Engineer salary is:"+s.salary);
System.out.println("Bonus of Software_Engineer is:"+s.bonus);
}
}

The example shown above says that the Software_Engineer object can access the field of its own class and of the Employee class, i.e., code reusability.

Get 100% Hike!

Master Most in Demand Skills Now!

Inheritance Types

These are the types of inheritance available in Java on the basis of the class:

  • Single inheritance
  • Multilevel inheritance
  • Hierarchical inheritance
  • Hybrid inheritance
  • Multiple inheritance using interfaces

Among them, multiple and hybrid ones are available by using interfaces only.

Note: Through classes, multiple inheritance is not supported in Java.

a. Single Inheritance

When one class inherits another class, it is known as single inheritance. Let’s have a look at the example given down below where the Sunflower class inherits the Flower class, so this would be a single inheritance.

Single Inheritance in Java
class Flower{  
void sweet(){System.out.println("sweet...");}  
}  
class sunflower extends Flower{  
void nature(){System.out.println("natural beauty...");}  
}  
class TestInheritance{  
public static void main(String args[]){  
sunflower s=new sunflower();  
sunflower.nature();  
s.sweet();  
}}  

b. Multilevel Inheritance

Whenever the chain of inheritance is present in the code, it is called multilevel inheritance. That means, ClassC is inheriting from ClassB, and ClassB is inheriting from ClassA.
Let’s have a look at the example given down below:

Multilevel Inheritance in Java
Class A
{
   public void methodA()
   {
     System.out.println("Class A method");
   }
}
Class B extends A
{
public void methodB()
{
System.out.println("class B method");
}
}
Class C extends B
{
   public void methodC()
   {
     System.out.println("class C method");
   }
   public static void main(String args[])
   {
     C obj = new C();
     obj.methodA(); //parent class method is called
     obj.methodB(); //class method is called
     obj.methodC(); //local method is called
  }

c. Hierarchical Inheritance

Whenever two or more classes inherit properties from a single class is known as hierarchical inheritance.

Hierarchical Inheritance in Java

Let’s have a look at the below example.

class X
{
   public void methodX()
   {
      System.out.println("method of Class X");
   }
}
class Y extends X
{
   public void methodY()
   {
      System.out.println("method of Class Y");
   }
}
class Z extends X
{
  public void methodZ()
  {
     System.out.println("method of Class Z");
  }
}
class W extends X
{
  public void methodW()
  {
     System.out.println("method of Class W");
  }
}
class JavaExample
{
  public static void main(String args[])
  {
     Y obj1 = new Y();
     Z obj2 = new Z();
     W obj3 = new W();
     //All classes can access the method of class X
     obj1.methodX();
     obj2.methodX();
     obj3.methodX();
  }
}

d. Hybrid Inheritance

It is a combination of both multilevel inheritance and single inheritance. However, we can achieve hybrid inheritance by using interfaces only.

Hybrid Inheritance in Java

Look at the example given below for hybrid inheritance:

public class ClassX
{
    public void dispX()
    {
        System.out.println("disp() method of ClassX");
    }
}
public class ClassY extends ClassX
{
    public void show()
    {
        System.out.println("show() method of ClassY");
    }
    public void dispY()
    {
        System.out.println("disp() method of ClassY");
    }
}
public class ClassZ extends ClassX
{
    public void show()
    {
        System.out.println("show() method of ClassZ");
    }
    public void dispZ()
    {
        System.out.println("disp() method of ClassZ");
    }
}
public class ClassW extends ClassY,ClassZ
{
    public void dispD()
    {
        System.out.println("disp() method of ClassD");
    }
    public static void main(String args[])
    {
          ClassW w = new ClassD();
          w.dispW();
          w.show();
    }
}

e. Multiple Inheritance Using Interfaces

When one class inherits properties from multiple classes, it is known as multiple inheritances.

Multiple Inheritance in Java

Example:

interface A {

  // It is an abstract class. 
  public void c();
}

class B {

  public void responsive(String str) {
    System.out.println(str + " can also be used as B.");
  }
}

// L extends B class
// L implements A interface
class L extends B implements A {

  String L = "Java";

  // implement method of interface
  public void C() {
    System.out.println(L + " can be used as A.");
  }

  public static void main(String[] args) {

    // create object of L class
    L java = new L();

    java.C();

    // call the inherited method of B class
    java.responsive(java.L);
  }
}

3. Polymorphism

Polymorphism helps an object take more than one form. We use polymorphism when parent class reference is used to refer to a child class object.

We can only access the object through a reference variable. A reference variable is only one type that is once declared cannot be changed. Those Java objects that can pass more than one IS-A test are referred to as polymorphic. Every object in Java is polymorphic because the object passes the IS-A test on its own and for the class Object.

Let’s have a look at the example given below:

public interface Veg{}
public class Animal{}
public class Duck extends Animal implements Veg{}

Now, the Duck class is referred to as polymorphic because it has multiple inheritance. The following points are true for the given example:

    • A Duck IS-A Animal
    • A Duck IS-A Veg
    • A Duck IS-A Duck
    • A Duck IS-A Object

The moment we apply the reference variable facts to the Duck object reference, here are the declarations that are legal:

Example:

Duck b = new Duck();
Animal a = b;
Veg x = b;
Object o = b;

These reference variables b, a, x, and o in the heap are pointing to the same Duck object.

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.