[英]Java : call a non-static field of an abstract class in conflict with an interface's field
[英]What is the correct way to assign Parent's static field values to Child's non-static field values?
我是編程新手,所以如果我的問題聽起來很愚蠢,請原諒。 但是,以下是我想要做的。 (目前我正在學習 Java 的 Comparable 和 Cloneable Interfaces)
我正在測試 Cloneable 和 Comparable Interface 在 java 中的工作方式,並為此創建了這兩個類:
類 1 --> 抽象類 --> GeometricShapes
類 2 --> 非抽象 --> 圓
我試圖創建具有唯一 ID 的 Circle 類的不同對象。
以下是我對這兩個類的代碼。 雖然,我能夠實現我想要的,但 vsCode 發出警告“應該以靜態方式訪問靜態字段 GeometricShapes.id” 。 所以我知道這不是做我想做的事情的最佳方式。
有沒有更好的方法來實現這一目標?
代碼:
public abstract class GeometricShapes {
protected static int id = 0;
protected String colour;
protected boolean filled;
protected java.util.Date creationDate;
protected GeometricShapes(String colour, boolean filled) {
id++;
creationDate = new java.util.Date();
this.colour = colour;
this.filled = filled;
}
protected abstract double getArea();
protected abstract double getPerimeter();
}
public class Circle extends GeometricShapes implements Comparable<Circle>, Cloneable {
private double radius;
private int circleID = super.id; //This is where the problem is
public double getRadius() {
return this.radius;
}
public Circle(String colour, boolean filled, double radius) {
super(colour, filled);
this.radius = radius;
}
@Override
public int compareTo(Circle arg0) {
if (this.radius > arg0.radius)
return 1;
else if (this.radius < arg0.radius)
return -1;
else
return 0;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public double getArea() {
return ((this.radius * this.radius) * Math.PI);
}
@Override
public double getPerimeter() {
return (2 * Math.PI) * this.radius;
}
@Override
public String toString() {
return ("Circle id: \t" + this.circleID + "\nCreated on: \t" + this.creationDate + "\nRadius: \t" + this.radius
+ "\nArea: \t\t" + this.getArea() + "\nPerimtr: \t" + this.getPerimeter());
}
public java.util.Date getCreationDate() {
return this.creationDate;
}
public int getID() {
return this.circleID;
}
}
定義兩個與 ID 號生成相關的字段。 定義一個static
字段,該字段指示創建新對象時要使用的下一個 Id。 每個新實例都會增加此值。 為該特定實例的實際 Id 定義另一個非static
字段。
public abstract class GeometricShapes {
/**
* Field for the next Id to use.
*/
private static int nextIdToUse = 1;
/**
* The Id of this geometric shape.
*/
private final int id;
protected GeometricShapes(String colour, boolean filled) {
this.id = nextIdToUse++;
// [...]
}
/**
* Returns the Id of this geometric shape.
*
* @return The Id.
*/
public int getId() {
return this.id;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.