Java Abstract Method

www.la‮u‬tturi.com
Java Abstract Method

In Java, an abstract method is a method that does not have an implementation and must be overridden by a subclass.

Abstract methods are declared in an abstract class or interface, and they do not have a body. Instead, they are followed by a semicolon (;).

Here is an example of an abstract method in an abstract class:

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.

To override an abstract method in a subclass, you must use the @Override annotation and provide an implementation for the method.

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.

It is important to note that if a subclass does not override an abstract method of its superclass, the subclass must also be declared as abstract.

Abstract methods are often used to define the interface of a class, and they are useful when you want to provide a common interface for a group of related classes.

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