Interface and Abstraction in java
from Head First Java chapter 08
As you know an OOP concept is interconnected with each other oop concepts. Based on this, this is chapter is talking about the interface and abstract class.
Inheritance makes polymorphism .abstrct class and interfaces help to achieve serious polymorphism and Abstraction.
Abstract class
- An abstract class is a class with abstract keywords.
- When you want to restrict your class to create a new instance, then you can make your class abstract.
- It can have non-abstract and abstract methods and can have constructor, data members also.
- When the abstract class is extended by the concrete class its abstract methods must be implemented in the concrete class.
- It can not create a new instance(instantiate).
- An abstract class can not be final and can not have private methods obviously.
- In class inheritance hierarchy, the first concrete class should implement the abstract methods of the super abstract class.
- The access modifier of the method in the subclass must not be less accessible than the superclass.
Abstract method
A method with an abstract keyword is known as the abstract method. The method can not have an implementation and ends with a semicolon.
An abstract method can not be in a non-abstract class.
based on the above class diagram:
The shape is an abstract class and it has instance methods getColor() and abstract method area(). The Circle and Triangle are subclasses of the Shape class
When you extend the Shape class, the subclasses must have to implement the method area() while the getColor() method can be overridden if you want.
You can not create a new instance directly from the abstract class but can create array elements as objects.
Interface
In java abstraction can be achieved in two ways,
- make a class abstract
- use interface
- The interface gives fully abstraction and gives solutions for multiple inheritance and code reuse.
- A class will implement the interface and an interface extends another interface.
- Methods in the interface are abstract. a have public and abstract modifiers implicitly.so You don't need to type it.
- The variables in the interface are public static and final implicitly.
- By interface can contain default and static methods also.
- The interface can not create instances directly same as the abstract class.
From the above class diagram: if the shape class is interfaced out code looks like
Here, the Circle class implements the Shape interface and have an implementation from the method area().