Abstract keyword in Java
Abstract
in java is used to represent that there is no concrete implementation.
The abstract
keyword in Java is used to declare a class or a method as abstract.
An " abstract class " can have abstract methods which have to be implemented by its concrete sub classes. An " abstract method " does not have concrete implementation or body, and must ends with a semicolon.
The following example declares a class “Employee” as abstract:
- public abstract class Employee {
- public abstract void job();
- }
public abstract class Employee { public abstract void job(); }
Keyword abstract should be used for declaring it. Should be implemented by concrete sub classes. Mandatorily we must declare the enclosing class as abstract class We can’t instantiate or create an object for the abstract class. In abstract classes we Can have both abstract and concrete methods. Example: Create Developer.java Example: static abstract example
In the above example, we can see that class “Employee” is declared as abstract and also method “job()” is declared as abstract.
Rules for Abstract class and Abstract Methods in Java
An abstract method:
Will not have body (method definition) and should end with a semicolon.
An abstract class:
The purpose of an abstract class is to keep common generic methods for a set of related sub-classes and make those sub-classes to provide the
specific method definition.
Now any class extending “Employee” abstract class has to provide the method definition to qualify as concrete class.public class Developer extends Employee {
public void job(){
//Do coding based on requirement
}
}
Create Tester.javapublic class Tester extends Employee {
public void job(){
//Do testing of application
}
}
Abstract class can have both abstract and concrete methodspublic abstract class Employee {
public abstract void job();
public void resign(){
//Follow same resignation process for all employees
}
}
Abstract methods cannot be declared as static and final.
Both the below examples are not valid in Java
public abstract class Employee {
public static abstract void job();
}
final abstract examplepublic abstract class Employee {
public final abstract void job();
}