标签:
封闭图像抽象类及其子类
public interface Area{ public double area(); }
public final class Circle extends Ellipse //圆类,最终类 { public Circle(double radius) //构造方法,radius参数指定圆的半径 { super(radius,radius); this.shape = "圆"; } public Circle() { this(0); } public String toString() { return "半径"+this.radius_a; } public static void main(String[] args) { new Circle(10).print(); } }
public abstract class ClosedFigure //闭合图形抽象类 { protected String shape; //形状 protected ClosedFigure(String shape) //构造方法,不能是抽象方法 { this.shape = shape; } protected ClosedFigure() { this("未知"); } public abstract double area(); //计算面积,抽象方法,以分号";"结束 public abstract double perimeter(); //计算周长,抽象方法 public void print() //显示形状、属性、周长及面积 { System.out.println("一个"+this.shape+","+this.toString() +",周长为"+this.perimeter()+",面积为"+this.area()); } } class ClosedFigure_ex { public static void main(String args[]) //抽象类中可以包含main()方法 { ClosedFigure g = new Ellipse(10,20); //g引用椭圆对象 g.print(); //显示椭圆属性 g = new Circle(10); //圆 g.print(); g = new Rectangle(10,20); //g引用矩形对象 g.print(); //显示矩形属性 g = new Square(10); //正方形 g.print(); } }
public class Ellipse extends ClosedFigure //椭圆类 { protected double radius_a; //a轴半径 protected double radius_b; //b轴半径 public Ellipse(double radius_a, double radius_b)//构造方法 { super("椭圆"); this.radius_a = radius_a; this.radius_b = radius_b; } public Ellipse() { this(0,0); } public String toString() { return "a轴半径"+this.radius_a+",b轴半径"+this.radius_b; } public double area() //计算椭圆面积,覆盖父类的抽象方法 { return Math.PI*this.radius_a*this.radius_b; } public double perimeter() //计算椭圆周长,覆盖父类的抽象方法 { return Math.PI*(this.radius_a+this.radius_b); } public static void main(String args[]) { new Ellipse(10,20).print(); } }
public class Rectangle extends ClosedFigure //矩形类 { protected double length; //长度 protected double width; //宽度 public Rectangle(double length, double width)//构造方法 { super("矩形"); this.length = length; this.width = width; } public Rectangle() { this(0,0); } public Rectangle(Rectangle r) { this(r.length, r.width); } public String toString() { return "长度"+this.length+",宽度"+this.width; } public double area() //计算矩形面积,实现父类的抽象方法 { return this.width*this.length; } public double perimeter() //计算矩形周长,实现父类的抽象方法 { return (this.width+this.length)*2; } public void setLength(double length) { this.length = length; } public void setWidth(double width) { this.width = width; } public double getLength() { return this.length; } public double getWidth() { return this.width; } public static void main(String args[]) { new Rectangle(10,20).print(); } }
public final class Square extends Rectangle //正方形是长方形的特例 { public Square(double width) { super(width,width); this.shape = "正方形"; } public Square() { this(0); } public String toString() { return "边长"+this.length; } public static void main(String[] args) { new Square(10).print(); } }
标签:
原文地址:http://blog.csdn.net/u011479875/article/details/45559321