我試圖通過嘗試幾件事情來了解Java。我在同一個包中使用了兩個類。一個叫Box
,另一個叫TestBox
。我想使用calculateArea()
來計算公司框的面積。此功能在另一個類TestBox
。但Box
中的功能calculateArea
不響應TestBox
中的功能。我錯過了這兩個類之間的鏈接。這看起來像一個簡單的問題,但我還沒有找到解決方案。有人可以幫我嗎?從java中的另一個類加入方法
package box;
public class Box {
int length;
int width;
public static void main(String[] args) {
Box company = new Box();
company.length = 3;
company.width = 4;
int area = company.calculateArea();
}
}
package box;
public class TestBox {
int length;
int width;
int calculateArea(){
int area = length * width;
System.out.println("Area= " + area);
return area;
}
}
「company」的類型(Read:Class)必須有一個名爲「calculateArea」的方法。 – folkol 2014-09-19 15:39:40
如果'calculateArea'屬於'TestBox'類,那麼你可以在這個類的實例上調用這個方法。因爲'Box'沒有'calculateArea'方法,所以你不能在'Box'實例上調用它(在'company'引用中保存。 – Pshemo 2014-09-19 15:40:17
我認爲你正在尋找'TestBox company = new TestBox();' – user1071777 2014-09-19 15:40:19