//抽象类abstract--like C++ 模板
abstract class Shape
{
protected String name;
public Shape(String xm)//抽象类中的一般方法,构造方法
{
name=xm;
System.out.print("名称"+name);
}
abstract public double getArea(); //声明抽象方法(只需声明)
abstract public double getLength(); //声明抽象方法
}
//
class Circle extends Shape //定义继承自Shape的子类Circle
{
private final double PI=3.14;
private double radius;
public Circle(String shapeName,double r) //构造方法
{
super(shapeName); //调用父类中的有参构造方法 必须在第一行
radius=r;
}
public double getArea() //实现抽象类中的方法
{
return PI*radius*radius;
}
public double getLength() //实现抽象类中的方法
{
return 2*PI*radius;
}
}
//
class Rectangle extends Shape //定义继承自Shape的子类Rectangle
{
private double width;
private double height;
public Rectangle(String shapeName,double width,double height)
{
super(shapeName);
this.width=width;
this.height=height;
}
public double getArea()
{
return width*height;
}
public double getLength()
{
return 2*width*height;
}
}
//
public class App8_10 { //主类
public static void main(String[] args)
{
Shape rect=new Rectangle("长方形",6.5,10.3);
System.out.println(";面积="+rect.getArea());
System.out.println(";周长="+rect.getLength());
Shape circle=new Circle("圆",10.2);
System.out.println(";面积="+circle.getArea());
System.out.println(";周长="+circle.getLength());
}
}
App8_10_抽象类abstract
最新推荐文章于 2021-09-13 14:39:54 发布