Abstract classes can be implemented in java. A class is declared abstract using the keyword "abstract" as a prefix. An abstract class may or may not contain any
abstract method. Now lets understand what exactly is an abstract class. Abstract class can be considered as a generic class implemented. Consider the following example :
Their are diffrent classes for various shapes like Rectangle,Square,Circle,Ellipse....
All share some comman properties like color,dimension,fillColor. These comman features/functionality can be kept in a generic class called Shapes. Also each individual class differs in size. Lets say each needs a method changeSize(), The method cannot be kept in superclass Shapes as each class has its own implementation and Shapes being a generic class does not requires this function. If we declare this function as abstract, its signature can be kept in the Shapes class. Each class which extends the Shapes class can write the changeSize method as per its own implementation.
Note that the same can be achieved using interfaces also, but interface cannot have implemenaion of the methods. So the comman methods would be required to be defined in all the classes implementing the interface. Interfaces will be discussed later in the blog,but for the time being just consider it as an implementaion of inheritance in java.
Some key points in abstract classes:
1.A subclass extending an abstract class may or may not define the abstract methods. To do so make the subclass itself as abstract.
2. Abstract class cannot be instantiated.
3. If implementation contains only method signatures and those methods need to be overridden in every sub class then make it as interface rather than abstract class.
An advantage of abstract class over interace is that abstract classes can contain concrete methods also. So in guture if a new method is to be introduced, just add it as a concrete method in abstract class and can be used by the subclass.
Abstract class example:
abstract class Shapes{
private String color; // Should have used Color class instead
public void setColor(String color){
.....
}
public void abstract changeShape(....); //No implementation
}
public class Rectangle extends Shapes{
public void changeShape(...){
//implement the specialises method
}
}
It can also be possible for a class not implementing all the abstract methods. Add another abstract method named "repostion" in Shapes class.
Now do as followed
abstract class Rectangle extends Shapes{
public void changeShape(...){
//implement the specialises method
}
}
class AnotherClass extends Rectangle {
public void reposition(){
//implemet method here
}
}
The above class contaiins all the abstract methods of the Shapes class which were not implemented by Rectangle class.
For more details on abstract class click here .
For comparison between abstract class and interface click here
No comments:
Post a Comment