Java Abstract Class and Method

www.‮l‬autturi.com
Java Abstract Class and Method

In Java, an abstract class is a class that contains one or more abstract methods, which are methods that do not have an implementation.

Abstract classes cannot be instantiated, which means that you cannot create objects of an abstract class using the new operator.

Instead, you can create a subclass of the abstract class, and the subclass must override the abstract methods of the superclass and provide an implementation for them.

Here is an example of an abstract class and an abstract method 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 an abstract method called getArea. The getArea method does not have an implementation, and it must be overridden by a subclass.

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 to provide an implementation that calculates the area of a circle.

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