Abstract classes in java are the classes that contain abstract mehtods, and abstract methods are the methods which do not contain any implementation.
We know that the meaning of abstract is something that only exists in thoughts, similarly a method that only has declaration but not implementation are called absract methods.
Even a single abstract method would make the whole class abstract i.e. an abstract class can contain both normal methods and abstract methods, even if there's a single method that is abstract in any normal class, we have to declare the whole class as abstract.
See the example below to understand it further.
Example:
Here Animal is an abstract class with two abstract methods, sound() _and _feet() _ and a normal method _breathe(). The working of method breathe would be same for every animal so it was written as a normal class. Whereas animal's make different sounds and have different number of legs, so these properties would differ for every animal and hence they are not initialized in the class animal itself but in the derived classes. So we can say that basically the abstract methods provide blueprint.
And their working could be understood making object of each class.
Output:
Interface:
Interfaces are similar to abstract classes, as they also contain methods with only declaration and not implementation
This is code for interface, which act as a blueprint for all the shape classes that would be further derived from this.
In interface each method is automatically public and abstract method. So unlike the abstract class which can contain both normal as well as abstract methods, in interface all the methods are automatically abstract.
So interfaces are used to create a blueprint of all the methods should be in its derived classes
To derive a class from interface we use implement keyword, like we use extends for normal classes.
Top comments (0)