[英]Accessing variables in Java Constructor and using in rest of class
So this is a rather simple question I'm sure for java and been answered before, I just can't seem to exactly find this answer. 因此,这是一个相当简单的问题,我确定对于Java来说,它已经在之前得到了回答,我似乎无法确切找到此答案。 Prefer if someone could just comment the answer. 如果有人可以评论答案,则更喜欢。
If you have 如果你有
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;
}
So basically I have points defined to take two variables x and y and I'm trying to calculate this area of a triangle. 因此,基本上,我已将点定义为采用两个变量x和y,并且试图计算三角形的这一面积。 So someone gives 3 points to make this triangle and I'm trying to get those values from the points and I do have getters for my points but I'm just ending up with nothing for length and width. 所以有人给了3个点使这个三角形,我试图从这些点中获得这些值,我的点确实有吸气剂,但最后却没有长度和宽度。
If you want code outside of A
to be able to access newid
, then you need to add getter and/or setter methods to A
. 如果你想之外的代码A
来能够访问newid
,那么你需要getter和/或setter方法添加到A
。
For example: 例如:
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;
}
}
Note that the this.
注意this.
qualification is not necessary in this particular example. 在此特定示例中,没有必要进行限定。
On the other hand, if you want to access newId
within the class A
, then ... 另一方面,如果要访问类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.