Abstract Classes
- Eclipse: Oxygen
- Java: 1.8
In Java, Abstract classes are created by using the abstract keyword in the class definition.
Syntax
1 2 3 |
public abstract class Person { } |
Some facts related to Abstract class in Java
- An abstract class is used to achieve abstraction. A class that is declared with the abstract keyword is known as an abstract class in Java.
- It can have abstract and non-abstract methods (method with the body).
- An abstract class can have abstract and concrete methods both.
- An abstract class cannot be instantiated, it means we cannot create an object of the class. We need a different class for the implementation of the abstract class.
Let’s see the implementation of the abstract class
In the following example, we have an abstract class “Person” which has an abstract method “eat”.
1 2 3 4 5 6 7 |
public abstract class Person { public void speak() { System.out.println ("share his/her thoughts"); } public abstract void eat(); } |
Note: A class must be an abstract class to contain an abstract method.
A concrete class (a class which does not contain any abstract method in it) must extend the abstract class to implement the abstract method. As soon as we extend an abstract class, Java displays an error message to implement the abstract method of the class.
We have two concrete class which extends Person class and implement the abstract method “eat” as per the requirement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Vegan extends Person { @Override public void eat() { System.out.println ("Eats Vegan"); } } class NonVegan extends Person{ @Override public void eat() { System.out.println ("Eats Vegan"); } } |
1 2 3 4 5 6 7 8 9 10 |
public static void main(String[] args) { Person john = new Vegan(); john.speak(); john.eat(); System.out.println("======================="); Person mia = new NonVegan(); mia.speak(); mia.eat(); } |
Output
share his/her thoughts
Eats Vegan
=======================
share his/her thoughts
Eats NonVegan
Contributed by: Poonam Tomar