Shape类有zhouchang()和area()两种方法。 Rect有cha()用于比较长宽的差,若长大于宽输出“长比宽大”,否则输出“宽比长大”。(正方形)Squ为Rect子类,在Squ类中,重写cha()方法,并输出“长等于宽” 要求:(1)要提供Circle和Rect类要重写父类Shape的zhouchang()和area()方法 (2)Circle类要有静态常量PI (3)为Circle类,Rect类,Squ类提供构造方法,为属性赋初值 (4)编写测试类,测试上述程序注意:学习完抽象类后,将该题目中的Shape类改为抽象类,将该类中的zhouchang()方法和area()方法定义成抽象方法
package javasky; public abstract class Shape { private double dLong = 0.00; private double width = 0.00; private double height = 0.00; public double getDLong() { return dLong; } public void setDLong(double long1) { dLong = long1; } 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 void girth() { } public void area() { } } package javasky; public class Circle extends Shape { private final static double PI=3.14; @Override public void area() { System.out.println( this.getDLong()); } @Override public void girth() { System.out.println( this.getDLong()); } } package javasky; public class Rect extends Shape { @Override public void area() { System.out.println("面积为:"+this.getDLong()*this.getWidth()); } @Override public void girth() { System.out.println("周长为:"+(double)2*this.getDLong()+(double)2*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.println("赋初始值"); this.setDLong(dlong); this.setWidth(width); } } package javasky; public class T { public static void main(String[] args) { Rect rect = new Rect(2.00,2.00); rect.cha(); } }
建立一个Shape类,有Circle(圆形)和Rect(矩形)子类
最新推荐文章于 2024-10-23 14:59:54 发布