?? cuboid1.java
字號:
//【例4.2】 長方體類繼承長方形類并實現立體圖形接口。
public class Cuboid1 extends Rectangle2 implements SolidGraphics1 //長方體類
{
protected double height; //高度
public Cuboid1(double length, double width, double height) //構造方法
{
super(length, width);
this.height = height;
}
public Cuboid1(Rectangle2 r1, double height)
{
this(r1.length, r1.width, height);
}
public Cuboid1(double width)
{
this(width, width, width);
}
public Cuboid1()
{
this(0,0,0);
}
public double area() //計算長方體的表面積,覆蓋父類方法
{
return super.perimeter() * this.height;
}
public double perimeter() //雖然不需要計算周長,但需要覆蓋父類方法,否則產生邏輯錯誤
{
return 0;
}
public double volume() //計算長方體的體積,覆蓋接口中的抽象方法
{
return super.area() * this.height;
}
public void print() //顯示,覆蓋父類方法
{
System.out.print("一個長方體,長度為 "+this.length+",寬度為 "+this.width+",高度為 "+this.height);
// System.out.print(",周長為 "+this.perimeter());
System.out.println(",表面積為 "+this.area()+",體積為 "+this.volume());
}
public static void main(String args[])
{
Cuboid1 c1 = new Cuboid1(10,20,30);
c1.print();
}
}
/*
程序運行結果如下:
一個長方體,長度為 10.0,寬度為 20.0,高度為30.0,表面積為 1800.0,體積為6000.0
*/
/*
程序錯誤:
1、本類必須覆蓋方法area(),計算長方體的表面積。如果沒有覆蓋area()方法,程序仍然可運行,但計算的是長方形面積,而不是長方體的表面積。運行結果如下:
一個長方體,長度為 10.0,寬度為 20.0,高度為30.0,表面積為 200.0,體積為6000.0
public final double perimeter() //計算長方形周長,實現接口中的抽象方法,最終方法
{
return (this.width + this.length)*2;
}
public double area() //計算長方體的表面積,覆蓋父類方法
{
return this.perimeter() * this.height;
}
2、Java的多重繼承機制在語法上也存在二義性。如果
public interface SolidGraphics1 //立體圖形接口
{
// double length=0.0; //長度
public double area(int i); //計算長方形面積,覆蓋接口中的抽象方法
public abstract double volume(); //計算體積
}
編譯時能夠檢查出成員變量的二義性,例如,下列語句出錯:
System.out.print("一個長方體,長度為 "+this.length+",寬度為 "+this.width+",高度為 "+this.height);
成員方法的二義性對程序運行沒有影響。
//reference to length is ambiguous, both variable length in Rectangle2 and variable length in SolidGraphics1 match
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -