用关键字abstract修饰一个方法,并且只“声明”而不具体实现这个方法,就可以生成一个抽象方法。
包含至少一个抽象方法的类,且用abstract修饰,称为抽象类。
下面给用代码具体讲述
package com.mec.about_abstract.core;
public abstract class Shape {
protected String name;
public Shape(String name) {
this.name = name;
}
public abstract double perimeter(); //定义一个抽象方法
public abstract double area(); //定义一个抽象方法
@Override
public String toString() {
return name;
}
}
第三行,用abstract关键字声明Shape类是抽象类;
第十行、十一行定义了两个抽象方法。
抽象类是不能直接实例化的,因为抽象类存在未实现的方法。
由抽象类派生出来的子类,如果依然没有实现其抽象方法,则,这个子类也是抽象类
在Shape类基础上派生出来一个正方形类 Square类:
package com.mec.about_abstract.core;
/*Square类继承于Shape类,表示一个正方形
Shape是一个抽象类,Square实现了Shape的抽象方法
public abstract double perimeter();
public abstract double area();
*/
public class Square extends Shape {
private double sideLength; //正方形的边长属性
public double getSideLength() {
return sideLength;
}
public void setSideLength(double sideLength) {
this.sideLength = sideLength;
}
public Square(double sideLength) {
super("正方形");
this.sideLength = sideLength;
}
public Square() {
this(1.0);
}
@Override
public double perimeter() { //这是对基类抽象方法的实现
return 4 * sideLength; //按照正方形周长公式计算周长
}
@Override
public double area() { //这是对基类抽象方法的实现
return sideLength * sideLength; //按照正方形面积公式计算面积
}
}
下面再写一个长方形,继承Shape抽象类,实现其中的抽象方法
package com.mec.about_abstract.core;
public class Rectangle extends Shape {
//长方形的长和宽
private double width;
private double height;
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public Rectangle(double width, double height) {
super("长方形");
this.width = width;
this.height = height;
}
@Override
public double perimeter() { //这是对基类抽象方法的实现
return 2 * (width + height); //按照长方形周长公式计算周长
}
@Override
public double area() { //这是对基类抽象方法的实现
return width * height; //按照长方形面积公式计算面积
}
}
对上面写的正方形和长方形进行测验
package com.mec.about_abstract.test;
import com.mec.about_abstract.core.Rectangle;
import com.mec.about_abstract.core.Square;
public class Demo {
public static void main(String[] args) {
Square square = new Square(4.0);
System.out.println(square + "周长:"+ square.perimeter());
System.out.println(square + "面积:"+ square.area());
Rectangle rectangle = new Rectangle(5.0, 3.0);
System.out.println(rectangle + "周长:" + rectangle.perimeter());
System.out.println(rectangle + "面积:" + rectangle.area());
}
}
编译得到结果