gpt4 book ai didi

java - 如何在Java类方法中访问私有(private)变量

转载 作者:行者123 更新时间:2023-12-01 08:15:08 25 4
gpt4 key购买 nike

我正在尝试在我的方法 x 中访问私有(private)变量 ( distanceFromPoint )但似乎不起作用。我怎样才能访问它?我的方法返回 0.0无论其他值如何,始终如此。

代码

public class Pointdeclare {
private static int x;
private static int y;

Pointdeclare (int x_ , int y_ ){
this.x = x_;
this.y = y_;
}

int getX(){
return x;
}

int getY(){
return y;
}

static double distanceFromZero (){
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}

double distanceFromPoint(Pointdeclare point){
int distX = point.getX()- this.x;
int distY = point.getY()- this.y;

return (double) Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2));
}
}

主类

public class main {
static Pointdeclare p1 = new Pointdeclare(6, 7);
static Pointdeclare p2 = new Pointdeclare(3, 7);

public static void main (String[] args){
System.out.println(p2.distanceFromZero());

System.out.print(p1.distanceFromPoint(p2));
}
}

最佳答案

这对你来说会更好:

package cruft;

/**
* Point2 description here
* @author Michael
* @link http://stackoverflow.com/questions/14087002/how-to-access-private-variables-in-a-java-class-method
* @since 12/29/12 6:52 PM
*/
public class Point2 {

private int x;
private int y;

Point2(int x_, int y_) {
this.x = x_;
this.y = y_;
}

int getX() {
return x;
}

int getY() {
return y;
}

double distanceFromZero() {
return distanceFromPoint(new Point2(0, 0));
}

double distanceFromPoint(Point2 point) {
int distX = point.getX()-this.x;
int distY = point.getY()-this.y;

return (double) Math.sqrt(Math.pow(distX, 2)+Math.pow(distY, 2));
}


public static void main(String[] args) {
Point2 p1 = new Point2(6, 7);
Point2 p2 = new Point2(3, 7);
System.out.println(p2.distanceFromZero());
System.out.print(p1.distanceFromPoint(p2));
}
}

关于java - 如何在Java类方法中访问私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14087002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com