Browse by Domains

Abstract Class and Encapsulation in JAVA

Java is an object-oriented language. It enables us to organise our program into simpler logical units known as objects and offers abstraction, encapsulation, inheritance and polymorphism.

OOP is a methodology by which one can design a program by implementing classes and their objects.

What is Abstract Class ? 

An abstract class is a class that deals with the abstraction of our program. So, the question arises what abstraction is?

In general terms, Abstraction is that the feature of object-oriented programming that “shows” only essential information and “hides” unnecessary information. The foremost purpose of abstraction is to hide the unnecessary details from the users. Abstraction is selecting data that is beneficial and relevant for the user from a much bigger pool of information. 

In object-oriented programming, through abstraction, the programmer tries to ensure that only the functionality is provided to the user. All its implementation and other extraneous aspects are kept hidden to reduce complexity and increase the program’s efficiency.

  • A class that is declared by using an abstract keyword is known as the Abstract class. 
  • An abstract class cannot be instantiated, i.e., one cannot create an object (instance) from the class. 
  • An abstract class is permitted to have both abstract and non-abstract methods.
  • A class is needed to be declared as an abstract class if it contains abstract methods.
  • In order to use an abstract class, one can extend its child class and provide implementation to all of the abstract methods in its parent class.

Declaring an Abstract Class in Java

In Java, we declare that a class is abstract just by adding the abstract keyword preceding the class declaration. 

Here is a Java abstract class example:

public abstract class Person {

  }

This is how an abstract class is meant to be declared in Java. 

Now, when we try to create the instance of the Person class and try to compile it, the Java compiler will generate an error saying that an Abstract class cannot be instantiated.

Person personInstance = new Person();  //not valid

Abstract Methods

Abstract methods are meant to be used by abstract classes only. Abstract methods are methods without the body. An abstract class may have both abstract methods and regular methods.

While declaring a method abstract, we add the abstract keyword in front of the method declaration and the method is ended with the semicolon (;).

Here is a Java abstract method example:

public abstract class Person {

public abstract void myJob();

  }

An abstract method has no body or implementation. Only the signatures of the method which are going to be implemented by the subclasses are present.

If a class contains an abstract method, the whole class must be declared as the abstract class. Not all methods in an abstract class are necessary to be abstract methods. An abstract class can have a mixture of both abstract and non-abstract methods.

Subclasses of an abstract class are bound to implement (override) all abstract methods of its corresponding abstract superclass. The non-abstract methods of the superclass are just inherited as they are with the help of the super keyword. They can also be overridden if required.

Here is an example subclass “Teacher” of the abstract class “Person”:

public class Teacher extends Person {

public abstract void myJob(){

System.out.println(“My job is Teaching.”);

  }}

Notice how the subclass “Teacher” has to implement the abstract method myJob() from its abstract superclass “Person”.

When a subclass of an abstract class is not required to implement all abstract methods of its superclass, the only time the subclass is also an abstract class.

Purpose of Abstract Classes

The main purpose of abstract classes is to function as the base classes, which are to be extended by their subclasses in order to create their full implementation.

For instance, we have a superclass person with a method myJob(), and the subclasses are like Teacher, Painter, Singer etc. Since every person’s job corresponds to different professions isn’t the same, there is no point in implementing this method in the parent class. This is because every subclass/child-class must override this method to give its implementation details like Teacher class will do “Teaching” in this method, and Painter class will do “Painting”, etc.

So, when we are aware that all the Person child classes will and requisite to override this myJob() method, there is no point in implementing this method in the parent class. Thus, making this method abstract would be a decent choice. By making this method abstract, we have made it compulsory for all subclasses to implement this method; otherwise, we will encounter the compilation error. Whenever the method is abstract, we don’t need to implement any method in the parent class.

Since the Person class has an abstract method, you just need to declare this class abstract.

Each person must have a job; hence by making this method abstract, we made it compulsory for the child class to give implementation details to this method. From this way we have ensured that every Person has a Job.

Abstract class Example

//abstract parent class
public abstract class Person{ 
//abstract method
public abstract void myJob();
}
//Teacher class extending Person class
public class Teacher extends Person {
public abstract void myJob(){
System.out.println(“My job is Teaching.”);
  }}
//Painter class extending Person class
public class Painter extends Person {
public abstract void myJob(){
System.out.println(“My job is Painting.”);        }}
Public static void main(String args[]){
Person obj;
obj = new Teacher();
System.out.println(“TEACHER-” + obj.myJob());
obj = new Painter();
System.out.println(“PAINTER-” + obj.myJob());
}

OUTPUT:

TEACHER-My job is Teaching.

PAINTER-My job is Painting.

Hence, for such kinds of real-world scenarios, we generally declare the class as abstract, and later, concrete classes extend these classes and override the methods accordingly. They can have their methods as well.

What is Encapsulation?

Encapsulation is defined as the wrapping or bundling up of data and methods of a class into a single unit. The fundamental concept of encapsulation is to hide the internal representation of an object from the outside. This is also known as data hiding. In general, encapsulation restricts the outer classes to access and modify the fields and methods of a class.

Data Hiding in Java

Data Hiding in Java is defined as the mechanism to hide the variables of a class from other classes. Access to these variables is only granted through the methods of the corresponding class. Apart from hiding the implementation details from the users, it also offers better management and grouping of related data.

In order to achieve a lesser degree of encapsulation in Java, we can use the access modifiers like “protected” or “public”. 

It allows us to modify a part of the code without affecting the other attributes.

How to Encapsulate the data?

If we use the most restrictive access modifier, i.e. private, we can only access it within the same class with our attribute or method.

Any other subclasses or classes within the same package will not be able to access the “private” variables or methods.

And if we want to get information about the current state of the object, we need to declare all the getter and setter methods as public.

Steps to achieve encapsulation in Java are −

  • Firstly, declare the variables of a class as private so that no other class or object can access them.
  • Secondly, we need to provide public setter and getter methods to modify(write-only) and view(read-only) the values of the private variables.

Encapsulation Demo:

The program to access variables of the class Employee is shown below:  

// Encapsulation Demo
class Employee {
    // Declare all the variables as private
    // these can only be accessed by
    // public methods of Employee class
    private String empName;
    private int empID;
    private int empSalary;
 
    // Setting up getters 
    // get method for salary to access
    // private variable empSalary
    public int getSalary()     {
             return empSalary;   }
 
    // get method for name to access
    // private variable empName
    public String getName() {
           return empName;   }
 
    // get method for ID to access
    // private variable empID
    public int getID() { 
             return empID; }
 
    // set method for employee salary to access
    // private variable empSalary
    public void setSalary(int newSalary) { 
             empSalary = newSalary; }
 
    // set method for employee name to access
    // private variable empName
    public void setName(String newName)
    {
        empName = newName;
    }
 
    // set method for employee ID to access
    // private variable empID
    public void setID(int newID) { empID = newID; }
}
 
public class TestEmployee {
    public static void main(String[] args)
    {
        Employee obj = new Employee();
 
        // setting values of the variables
        obj.setName("Sunny");
        obj.setSalary(10000);
        obj.setID(20);
 
        // Displaying values of the variables
        System.out.println("Employee's name: " + obj.getName());
        System.out.println("Employee's salary: " + obj.getSalary());
        System.out.println("Employee's ID: " + obj.getID());
 }}
        // Direct access of empID is not possible
        // due to encapsulation
        // System.out.println("Employee's ID: " + obj.empID);

OUTPUT:

Employee’s name: Sunny

Employee’s salary: 10000

Employee’s ID: 20

Also Read: Top 160+ Java Interview Questions and Answers in 2021

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

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

Great Learning Free Online Courses
Scroll to Top