Abstract Class in Java


An abstract class is a class marked with the abstract keyword. It, contrary to non-abstract class, may contain abstract - implementation-less - methods. It is, however, valid to create an abstract class without abstract methods.

An abstract class cannot be instantiated. It can be sub-classed (extended) as long as the sub-class is either also abstract, or implements all methods marked as abstract by super classes.

Abstraction can be achieved with either abstract classes or interfaces .

  • Abstract class must have one abstract method.
  • We can’ts create object using abstract class.
  • Abstract class can have abstract and non abstract methods.

This is a Java program that demonstrates the concept of abstract classes and abstract methods.

  • First, there is an abstract class called Shape that contains an abstract method called draw() and a non-abstract method called message(). The draw() method has no implementation, so any class that extends Shape will have to implement it. The message() method, on the other hand, has an implementation, so any class that extends Shape can use it as is.
  • Next, there is a class called rectangleShape that extends Shape and provides an implementation for the draw() method. It also inherits the message() method from its parent class.
  • Finally, in the main() method, an object of the rectangleShape class is created and its draw() and message() methods are called. The draw() method of rectangleShape is executed, while the message() method of Shape is executed because it was not overridden in rectangleShape.

This program demonstrates how abstract classes and abstract methods can be used to create a base class with certain methods that must be implemented by its subclasses, while also providing some methods with default implementations that can be used as is.

Source Code

//Abstract Class in Java Programming
abstract class Shape
{
    abstract void draw();
    void message()
    {
        System.out.println("Message From Shape");
    }
}
class rectangleShape extends Shape
{
    @Override
    void draw() {
        System.out.println("Draw Rectangle Using Length & Breadth..");
    }
}
 
public class abstractDemo {
    public static void main(String args[]) {
        rectangleShape o =new rectangleShape();
        o.draw();
        o.message();
    }
}

Output

Draw Rectangle Using Length & Breadth..
Message From Shape
To download raw file Click Here

Basic Programs