- Abstract Keyword used for method declaration which doesnt have any implementation.
- Abstract classes have abstract methods not having method implementation in the abstract class but in subclass.
- When a class doent need to get instiated then that class is used as an abstract class. But this class is available for others to get exextended and use functionality.
- The best example is the shape class.
- The shape class having the method called area in its declaration.
- which is different for all shapes class like it is different for squre, triangle, circle. each class inherits the shape class contains the functionality of that class ut it has to implement all "abstract methods" of the Shape class.
- Abstract class needs to be extended first to instanciatiate.
- Implementation
abstract ClassName()
{
abstract returntype MethodName1(Arg);
//This method needs to be iimplemented if this class is inherited.
ret_type MethodName2();
MethodName2()
{
}
}
- Example:
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){
System.out.println("Drawing Rectangle");
}
}
class Traingle extends Shape{
void draw(){
System.out.println("Drawing Traingle");
}
}
class AbstractDemo{
public static void main(String args[]){
Shape s1=new Rectangle();
s1.draw();
s1=new Traingle();
s1.draw();
}
}
Result:
Drawing Rectangle
Drawing Traingle