Java Tut – Abstraction

In OOP abstraction is a process of hiding the implementation details from the use, only the functionality will be provided to the user.In other words user will have the information on what the object does instead of how it does it.

In java abstraction is achieved using abstract classes, and interfaces.
Abstract Class:
A class which contains the abstract keyword in its declaration is known as abstract class.

– Abstract classes may or may not contain abstract methods ie. methods with out body( public void get(); )

– But if a class have at least one abstract method,then the class must be declared abstract

– If a class is declared abstract it cannot be instantiated
– To use an abstract class you have to inherit it from another class, provide implementations to the abstract methods in it.
– If you inherit an abstract class you have to provide implementations o all abstract methods in it

Example:

public abstract class Employee
{
private ...

//everything will be same 

}

and from another class

public class AbstractDemo{
public static void main(String[] args)
{
Employee e = new Employee("helda","washington",3);
System.out.pritln("Call");
e.mailCheck();
}
}

It will show error because of abstract class:

Employee.java:46: Employee is abstract; cannot be instantiated
      Employee e = new Employee("George W.", "Houston, TX", 43);
                   ^
1 error

Abstract Method:

public abstract class Employee
{
private String name;
private String addresss;
private int number;

public abstract double computePay();
//Remainder of class definition
}

Declaring a method as abstract has two consequences:

  • The class containing it must be declared as abstract.
  • Any class inheriting the current class must either override the abstract method or declare itself as abstract.

Eventually a descendant class has to implement the abstract method; otherwise you would have a hierarchy of abstract classes that cannot be instatiated.

Suppose salary class is inherits the Employee class, then it should implement the computePay() method as shwon below:
//will add the code later

references:
http://www.tutorialspoint.com/java/java_abstraction.htm

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

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