Using Abstract Classes
Using Abstract Classes
• There are situations in which you will want to define a superclass that
declares the structure of a given abstraction without providing a
complete implementation of every method.
• That is, sometimes you will want to create a superclass that only
defines a generalized form that will be shared by all of its subclasses,
leaving it to each subclass to fill in the details. Such a class determines
the nature of the methods that the subclasses must implement.
• abstract keyword in front of the class keyword at the beginning of the
class declaration.
• There can be no objects of an abstract class.
• abstract class cannot be directly instantiated with the new operator.
• we cannot declare abstract constructors, or abstract static methods.
• Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be declared abstract itself.
• // A Simple demonstration of abstract.
• abstract class A {
• abstract void callme();
• // concrete methods are still allowed in abstract classes
• void callmetoo() {
• System.out.println("This is a concrete method."); } }
• class B extends A {
• void callme() {
• System.out.println("B's implementation of callme."); } }
• class AbstractDemo {
• public static void main(String[] args) {
• B b = new B();
• b.callme();
• b.callmetoo();
• }
•}
• OUTPUT:
• B's implementation of callme
• This is a concrete method
6.Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that
extend the Shape class and implement the respective methods to calculate the area and perimeter of each shape.