您可以使用继承这个问题在下列方式:
声明一个名为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
你为什么不创建一个抽象类(形状例如),添加字段,这个类,让你的其他类扩展呢? –