//图形类 class Graphic{ private String name; //不使用无参数的构造方法 使用有参数的构造方法 public Graphic(String name){ super();//父类初始化 object基类 所有类的祖先 this.name=name; } public void setName(String name){this.name=name;} public String getName(){return name;} //获取面积的方法 每一个图形计算方法 都不一样 public double getArea(){ return 0.0; } public double getPerimeter(){return 0.0;} public String getInfo(){ //获取图形信息 return "图形名字:"+name+"面积:"+getArea()+"周长:"+getPerimeter(); } } //圆类 继承 图形类 class Circle extends Graphic{ private double radius; public Circle(String name,double radius){ super(name); //调用父类的有参数构造方法 this.radius=radius; } public void setRadius(double radius) { this.radius = radius; } public double getRadius() { return radius; } @Override public double getArea() { //重载父类的方法 获取面积 return Math.PI*radius*radius; } @Override public double getPerimeter() { //获取周长 return 2*Math.PI*radius; } @Override public String getInfo() { //获取圆形类的信息 return super.getInfo()+"半径:"+radius; } } //长方形类 继承图形类 class Rectangle extends Graphic{ private double length; private double width; public Rectangle(String name,double length,double width){ super(name); this.length=length; this.width=width; } public double getC() { return length; } public void setC(double length) { this.length = length; } public double getS() { return width; } public void setS(double width) { this.width = width; } @Override public double getArea() { return length*width; } @Override public double getPerimeter() { return 2*length+2*width; } @Override public String getInfo() { return super.getInfo()+"长:"+length+"宽:"+width; } } public class TestGraphicDemo02 { public static void main(String[] args) { Circle c=new Circle("圆形",2); System.out.println(c.getInfo()); Rectangle r=new Rectangle("长方形",2,4); System.out.println(r.getInfo()); } }
面向对象继承的重载
最新推荐文章于 2024-09-04 15:29:36 发布