Java Abstract Class - The Coding Shala
Home >> Learn Java >> Java Abstract Class
Abstraction in Java
Abstraction is an important pillar of object-oriented programming language. Abstraction is a process of hiding the implementation details and only showing the functionality to the user. Let's take an example Car. A user only knows how to drive, how to use breaks, how to change gears not all the details of how breaks work and how gear works. In Java when we know what object does not how the object does it, is called Abstraction.
There are two ways to achieve abstraction in Java:
- Abstract class
Java Abstract class
A class that is declared as abstract is known as an abstract class. We use the abstract keyword to declare an abstract class. An abstract class can have an abstract and non-abstract method. Abstract classes have partial implementation. We have to extend abstract classes to subclass and implement all the abstract methods in the subclass.
Java Abstract Method
A method which is declared as abstract and does not the implementation is known as an abstract method. A subclass must have to override an abstract method to provide the implementation.
The following syntax is used to declare the abstract class and abstract method in Java:
The following are important points to remember for Java Abstract classes:
- Abstract classes must be declared with an abstract keyword.
- Abstract classes can have abstract and non-abstract methods.
- Abstract classes can have constructors and static methods also.
- Abstract classes can have final methods also.
- If a class contains an abstract method then that class must be abstract.
- A class can not be declared with both final and abstract keywords. The final keyword is used to prevent overriding whereas abstract methods need to be overridden.
- Abstract classes can not be instantiated. We can not create an object of abstract classes. It can only be used as a reference.
Example of Java Abstract class
The following example explains the Java Abstract class:
An abstract class can have a constructor also. A constructor of an abstract class called when an instance of child class is created. An abstract class can have no-abstract method also. The following example explains it:
NOTE: if abstract class has final methods then final methods can not be overridden in child class.
An abstract class can exist without any abstract method but when an abstract method is there is a class then the class must be abstract. The following example explains it:
Question: Is it possible to create an abstract and final class in Java?
Answer: No, the final class can not have an abstract class because final classes can not override.
Question: Is it possible to have an abstract method in a final class?
Answer: No, when we declare an abstract method in a class the class automatically became abstract.
Other Posts You May Like