In this tutorial, I will introduce you to the abstract class in java.
What is Abstract Class in Java?
An abstract class is almost similar to the interface but the implementation of the method is different.
How to Create Abstract Class?
When we create an Abstract class in Java then we have to write an abstract method in that class.
In abstract class, we create a method with abstract keywords without its body.
In general other
The abstract class body must contain an abstract class without
Syntax to Create Abstract Class in Java:
Following are the syntax
In order to create an abstract class, you must write the abstract class according to the following procedure.
public abstract class ClassName{
instance variables;
public abstract methodName( );
}
for example to create a method in abstract class we write:
public abstract void add ( );
Example of Abstract Class:
Now I am going an example that how to create an abstract class step by step.
So open your IDE like NetBeans, Intellij Idea, or any other you want. I am using Net beans.
I have created two classes one is Super class which is Animal class.
see in the pic below.
Another class that I have created is the Cat class which is inherited from the super Animal Class.
See in the pic below:
Example of an abstract class body:
As I mentioned above that I have created two classes one is super and another is child class.
But I mean two create two classes here is two understand the abstract concept through an example.
As you see in the above example that When I created a class Animal with an abstract keyword then you will have generated an idea in your mind that whenever you create an abstract class you have to write an abstract keyword before it.
Another idea is that as I have given in the
When we want to create an abstract method body then we have to create in child classes just like I have just declared the setName( ) method in superclass which is Animal class and the body is declaring in child class which is animal class.
Important point to remember for creating Abstract class:
Following are the important points to remember for creating abstract classes and methods in Java.
- Abstract class cannot have it’s an object.
- A subclass is necessary for the abstract class. I mean to say that inheritance is necessary for abstract classes.
- The abstract methods of the abstract class must be implemented in all the classes.
- It’s necessary to create an abstract method for the abstract class.
- It’s not necessary for all abstract classes to create abstract methods for it.
- You cannot create abstract methods in other classes which is not abstract classes.
- Methods having abstract keywords can only be created within abstract classes.
I hope you understand about abstract class. Share with your friends. If you have any problem regarding this just comment below or you can contact me through my Facebook page.
Watch this picture for demonstration purposes: