Abstract class have their own importance in Java. Abstract classes works on the principle of generalization. They are created just that some other class extends them and implement its abstract methods. These classes cannot be instantiated and cannot have objects of their own. These classes works really well when it comes to Polymorphism. Generally concept of Polymorphism deals with single thing having more than one form. The abstract classes usually behave as more than one form for its sub classes. Abstract classes can have methods of their own, but it should have abstract methods so that derived class can implement those. The classes should be appended with a keyword called as abstract, to make it abstract by nature.
Program to demonstrate the use of Abstract class and Abstract method in Java
Output of the program :
Program to demonstrate the use of Abstract class and Abstract method in Java
package com.hubberspot.abstractTest.example; abstract class Shape { double a, b; Shape(double d1, double d2) { a = d1; b = d2; } abstract double area(); } class Circle extends Shape { Circle(double radius) { super(radius, 0); } double area() { return Math.PI * a * a; } } class Rectangle extends Shape { Rectangle(double length, double breadth) { super(length, breadth); } double area() { return a * b; } } public class AbstractTest { public static void main(String[] args) { Shape shape; shape = new Circle(5); System.out.println("Area of circle =" + " " + shape.area()); shape = new Rectangle(5, 10); System.out.println("Area of rectangle = " + shape.area()); } }
Output of the program :