Monday 25 June 2012

JAVA -abstract class and interface

Both Abstract class and interfaces are both like frameworks or outer skeleton .

They are to be implemented in child class which extends the parent class .

1) Interface is solely a skeleton .
Abstract class is not solely a skeleton , it also has implementations within it .

2) As interface is solely a skeleton , all methods inside a interface are abstract methods and variables are final and static .So , the implementing child class should implement all the methods inside the interface .
But when creating interface , we need not put the keyword abstract in front of all methods inside an interface as the definition of interface means it .
Abstract class can have within it, variables that are non static , methods that are not abstract  . So , the child class that implements the abstract class should implement all the abstract methods (if any ) . And leave the non abstract methods untouched .Needs to explicitly say which methods are abstract using keyword "abstract".
Neither abstract class nor interface can be instantiated . It can be only be implemented .
So if we don't implement all methods of interface and all abstract methods of an abstract class , then it means the child class that implements these child classes will also be considered as interfaces or abstract classes ,as they contain abstract methods which was inherited   (not implemented) and so the child classes cannot be instantiated , as abstract class and interface cannot be instantiated .

This brings in the idea that abstract classes and interfaces can be extended by other interface or class . A class that extends an interface must me either another interface or abstract class . So here all the methods of the interface need not be implemented in abstract class that extends it.

3) As the interface is solely abstract or skeleton , it is implemented by using keyword "implements" and not by using keyword "extends". As abstract may have implementations within it . It is implemented using keyword "extends "
In fact a interface can extend another interface using keyword "extends"


4) a child class can extend many interfaces at the same time , by separating interface names with "," .
a child class can extend only one abstract class .

No comments:

Post a Comment