您可以使用繼承這個問題在下列方式:
聲明一個名爲Shape的類,所有其他類將繼承
public class Shape {
public double length = 0;
public abstract double GetPerimeter();
public abstract double GetArea();
public Shape(double length) {
this.length = length;
}
}
然後讓你的專業課程。例如。 :
public class Circle extends Shape {
public Circle(double length) {
super(length);
}
public double GetPerimeter() {
// Implement the perimeter logic here
}
public double GetArea() {
// Implement the area logic here
}
}
對所有類都這樣做。這樣你只有一個類的變量,而其他所有的變量都從它繼承。
編輯
如果你想進一步優化(例如,你不希望函數調用的開銷),像或許
public class Shape {
public double length = 0;
public double perimeter= 0;
public double area= 0;
public Shape(double length, double perimeter, double area) {
this.length = length;
this.perimeter= perimeter;
this.area = area;
}
}
public class Circle extends Shape {
public Circle(double length) {
super(length, 2 * Math.PI * length, Math.PI * length * length);
}
}
像這樣的事情? https://stackoverflow.com/questions/20864211/how-to-get-a-variable-from-another-class-in-java – SassyRegards201
你不能繞過變量,只值。 – shmosel
你爲什麼不創建一個抽象類(形狀例如),添加字段,這個類,讓你的其他類擴展呢? –