Java Abstract Class

www.l‮a‬utturi.com
Java Abstract Class

In Java, an abstract class is a class that cannot be instantiated and is used to provide a common interface or implementation for its subclasses.

An abstract class can contain both abstract and non-abstract methods. Abstract methods are methods that do not have an implementation, and they must be overridden by a subclass. Non-abstract methods are methods that have an implementation and can be used by a subclass.

Here is an example of an abstract class in Java:

public abstract class Shape {
    private String color;

    public Shape(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public abstract double getArea();
}

In this example, the Shape class is an abstract class that contains a non-abstract method getColor and an abstract method getArea.

The getColor method has an implementation and can be used by a subclass, while the getArea method does not have an implementation and must be overridden by a subclass.

To create a subclass of an abstract class, you must use the extends keyword and override any abstract methods of the superclass.

Here is an example of a subclass that extends the Shape abstract class and overrides the getArea method:

public class Circle extends Shape {
    private double radius;

    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
}

In this example, the Circle class is a subclass of the Shape class, and it overrides the getArea method.

Created Time:2017-11-01 22:29:44  Author:lautturi