public abstract class Shape {
public Shape() {
}
public abstract void draw();
}
抽象類不一定意味著它具有至少一個抽象方法。
如果一個類有一個被聲明或繼承的抽象方法,它必須被聲明為抽象。
抽象方法的聲明方式與任何其他方法相同,只是它的主體由分號表示。
例子
下面的Shape類有抽象和非抽象方法。
abstract class Shape {
private String name;
public Shape() {
this.name = "Unknown shape";
}
public Shape(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// Abstract methods
public abstract void draw();
public abstract double getArea();
public abstract double getPerimeter();
}
下面的代碼展示了如何創(chuàng)建一個Rectangle類,它繼承自Shape類。
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
// Set the shape name as "Rectangle"
super("Rectangle");
this.width = width;
this.height = height;
}
// Provide an implementation for inherited abstract draw() method
public void draw() {
System.out.println("Drawing a rectangle...");
}
// Provide an implementation for inherited abstract getArea() method
public double getArea() {
return width * height;
}
// Provide an implementation for inherited abstract getPerimeter() method
public double getPerimeter() {
return 2.0 * (width + height);
}
}
更多建議: