‘abstract’ – a non access modifier
A non-access modifier is a keyword that changes the default behaviour of the Java Class.
An _ ‘abstract’ _ modifier can be applied to
1) ‘abstract’- Method modifier
- When an ‘abstract‘ keyword is prefixed to a method declaration, then the method becomes an abstract method:
public abstract void execute();
- A method with an empty body is not considered as an abstract method.
public void execute(){}
- An abstract method must appear in an abstract Class only.
abstract class Perform{ int x, y; public abstract String execute();
}
Abstract methods will be implemented by the derived Classes.
public class Action extends Perform{ public String execute(){
System.out.println("I am executing");
}
}
- If the derived class is not implementing the abstract method, then that Class also must be declared as an abstract Class.
public abstract class Action extends Perform{ public abstract String execute();
}
- Abstract methods can be used in the enums as well.
enum Model{
BENZ{
public String getModel(){ return "BENZ"; }
},
LAMBORGHINI{
public String getModel(){ return "LAMBORGHINI"; }
},
FERRARI{
public String getModel(){ return "FERRARI"; }
},
BUGATTI{
public String getModel(){ return "BUGATTI"; }
}
public abstract String getModel();
}
2) ‘abstract’ – Class Modifier
- When an ‘abstract‘ keyword is prefixed to a class definition, then the class becomes an abstract class.
abstract class Perform{
}
- An abstract Class may or may not have any abstract methods
abstract class Perform{
int x, y;
public abstract String execute();
}
(or)
abstract class Perform{
int x, y;
public String execute();
}
- An abstract class can’t be instantiated. If an attempt is made to instantiate the abstract class, ‘Perform is abstract, cannot be instantiated’ compilation error is thrown
3) ‘abstract’- Interface Modifier
- Every interface is implicitly abstract. Both the definitions below are the same.
interface Model{
}
(or)
abstract interface Model{
}
- Explicit use of an abstract keyword to an interface is redundant.
- Thus ‘abstract’ interface modifier is obsolete and not recommended to use in new programs.