因为第一期的代码和解释很清楚了,本次直接上代码
- 建立一个抽象Shape类,有Circle(圆形)和Rect(矩形)子类。Shape类有zhouchang()和area()两种抽象方法。
Rect类有cha()方法用于比较长宽的差,若长大于宽输出“长比宽大”,否则输出“宽比长大”。(正方形)Squ为Rect子类,在Squ类中,重写cha()方法,并输出“长等于宽”
要求:
- 要提供Circle和Rect类重写父类Shape的zhouchang()和area()方法。
- Circle类要有静态常量PI。
- 为Circle类,Rect类,Squ类提供构造方法,为属性赋初值。
- 编写测试类,测试上述程序。
1.创建Shape
public abstract class Shape { public abstract void zhouchang(); public abstract void area(); private double dLong = 0; private double width = 0; private double height = 0; public double getdLong() { return dLong; } public void setdLong(double dLong) { this.dLong = dLong; } 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; } }
2.创建Circle
public class Circle extends Shape{ static double IP=3.14; @Override public void zhouchang() { System.out.println(2*IP*this.getHeight()); } @Override public void area() { System.out.println(IP*IP*this.getHeight()); } public void cha() { System.out.print("圆的周长:"); zhouchang(); System.out.print("圆的面积:"); area(); } public Circle(double height) { System.out.print("自动赋值:"); this.setHeight(height); } }
3.创建Rect
public class Rect extends Shape{ @Override public void zhouchang() { // TODO Auto-generated method stub System.out.println("周长为:"+(double)2*this.getdLong()+(double)2*this.getWidth()); } @Override public void area() { // TODO Auto-generated method stub System.out.println("面积为:"+this.getdLong()*this.getWidth()); } public void cha() { double result = this.getdLong()-this.getWidth(); String shape="长为"+this.getdLong()+"宽为"+this.getWidth(); String str=""; if(result>0){ str=",此图形为长方形。"; } else{ str=",长等于宽,此图形为正方形。"; } System.out.println(shape+str); } public Rect(double dlong,double width) { System.out.print("自动赋值:"); this.setdLong(dlong); this.setWidth(width); } }
4.创建Squ
public class Squ extends Rect{ public Squ(double dlong, double width) { super(dlong, width); } private void cah() { //如果需要重写 } }
5.RectTest测试类
package test4; public class RectTest { public static void main(String[] args) { Rect rect = new Rect(25,20); rect.cha(); Circle circle=new Circle(10); circle.cha(); } }
运行截图: