簡體   English   中英

在Java Constructor中訪問變量並在其余的類中使用

[英]Accessing variables in Java Constructor and using in rest of class

因此,這是一個相當簡單的問題,我確定對於Java來說,它已經在之前得到了回答,我似乎無法確切找到此答案。 如果有人可以評論答案,則更喜歡。

如果你有

class Triangle{
private double x1,x2,x3,y1,y2,y3;
public Triangle(Point point1, Point point2, Point point3) 
{ 
x1=point1.getX();
y1=point1.getY();
x2=point2.getX();
y2=point2.getY();
x3=point3.getX();
y3=point3.getY();

//Trying to get x and y values of point1-point3

}

double width=x1-x2;
double length=y3-y2;

public double area() 
{ 
return (length * width)/2; 
} 

因此,基本上,我已將點定義為采用兩個變量x和y,並且試圖計算三角形的這一面積。 所以有人給了3個點使這個三角形,我試圖從這些點中獲得這些值,我的點確實有吸氣劑,但最后卻沒有長度和寬度。

如果你想之外的代碼A來能夠訪問newid ,那么你需要getter和/或setter方法添加到A

例如:

public class A {

    private int newid;

    public A(int id){
        this.newid = id;
    }

    public int getNewid() {
        return this.newid;
    }

    public void setNewid(int id) {
        this.newid = id;
    }
}

注意this. 在此特定示例中,沒有必要進行限定。

另一方面,如果要訪問類A newId ,則...

public class A {
    private int newid;

    ...

    public double b() {
       weight = newid * 5;
       // or 
       weight = this.newid * 5;
       ...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM