An abstract class is a class which cannot be instantiated. An abstract class is used by creating an inheriting subclass that can be instantiated. An abstract class does a few things for the inheriting subclass:
- Define methods which can be used by the inheriting subclass.
- Define abstract methods which the inheriting subclass must implement.
- Provide a common interface which allows the subclass to be interchanged with all other subclasses.
Here's an example:
package com.codetalk.abstractclass;
/**
* @author Rakesh KR
*
*/
abstract public class AbstractClass {
abstract public void abstractMethod();
public void implementedMethod(){
System.out.println("Implemented Method");
}
final void finalMethod(){
System.out.println("Final Method");
}
}
Here's a correct
ImplementingClass
package com.codetalk.abstractclass;
/**
* @author Rakesh KR
*
*/
public class ImplementingClass extends AbstractClass{
public void abstractMethod() {
System.out.println("Abastract Method");
}
public void implementedMethod(){
System.out.println("Overridden !!!");
}
/*
public void finalMethod(){
System.out.println(" Error !!! ");
}
*/
}
The implementation of
finalMethod()
in AbstractClass
is marked as the final implementation of finalMethod()
: no other implementations will be allowed, ever.
Now you can also implement an abstract class twice:
package com.codetalk.abstractclass;
/**
* @author Rakesh KR
*
*/
public class SecondImplementingClass extends AbstractClass{
public void abstractMethod() {
System.out.println("Second AbstractMethod");
}
}
Now the final class looks likes,
package com.codetalk.abstractclass;
/**
* @author Rakesh KR
*
*/
public class MainClass {
public static void main(String[] args) {
ImplementingClass a = new ImplementingClass();
SecondImplementingClass b = new SecondImplementingClass();
AbstractClass c = new ImplementingClass();
AbstractClass d = new SecondImplementingClass();
a.abstractMethod(); // prints "Abstract Method"
a.implementedMethod(); // prints "Overridden !!!"
a.finalMethod(); // prints "Final Method"
b.abstractMethod(); // prints "Second AbstractMethod"
b.implementedMethod(); // prints "Implemented Method"
b.finalMethod(); // prints "Final Method"
c.abstractMethod(); // prints "Abstract Method"
c.implementedMethod(); // prints "Implemented Method"
c.finalMethod(); // prints "Final Method"
d.abstractMethod(); // prints "Second AbstractMethod"
d.implementedMethod(); // prints "Implemented Method"
d.finalMethod(); // prints "Final Method"
}
}
Lastly, you cannot do the following:
public class ImplementingClass extends AbstractClass, SomeOtherAbstractClass {
... // implementation
}
Only one class can be extended at a time. If you need to extend multiple classes, they have to be interfaces. You can do this:
public class ImplementingClass extends AbstractClass implements InterfaceA, InterfaceB {
... // implementation
}
Comments
Post a Comment