Abstract Methods:
Abstract method is a method which does not have any body. It is defined with the keyword “abstract”. An abstract method must be overridden. This is something exactly opposite to final methods. It indirectly implies having child class for defining that method i.e. the class also should be declared as abstract class. Hence, abstract methods and abstract classes go hand in hand. To put it in simple words, when a class has an abstract method, the class also should be declared as an abstract class. Constructors and static methods can never be abstract.
Abstract classes:
Abstract classes are the classes which can be subclassed but not instantiated. An abstract class may have both abstract methods and normal methods. We cannot use abstract classes to instantiate objects directly. Abstract class objects can be instantiated using child classes. Abstract classes are used to design a common framework comprising a set of methods that have to be defined by all its child classes.
An abstract class is not required to have an abstract method in it. But any class that has an abstract method in it must be declared as an abstract class.
The following program demonstrates the usage of abstract methods and abstract classes.
abstract class Shape
{
abstract void draw( );
}
class Rectangle extends Shape
{
void draw()
{
…….
}
}
class Triangle extends Shape
{
void draw()
{
…….
}
}
class Test
{
public static void main(String as[])
{
Shape s1;
s1=new Rectangle();
s1.draw();
s1=new Triangle();
s1.draw();
}
}
0 comments:
Post a Comment