变量在调用函数中的可见性

huangapple go评论77阅读模式
英文:

variable visibility from calling function

问题

我有两个类。在一个类中,我有4个变量。我实例化另一个类并使用方法,这些方法使用这些变量。我不想将它们作为参数传递。它们被设置为public。两个类都位于相互之间的默认包中。这是我的代码:

public class c1 {
     public int x, y, x1, y1;
     public static void main(String args[]) {
          c1 a = new c1();
     }
     public c1() {
          c2 b = new c2();
          b.getSlope();
     }
}

public class c2 {
     public c2() {}
     public int getSlope() {
          return (y-y1)/(x-x1);
     }
}

我遇到一个错误,错误消息是:无法找到符号。

英文:

I have 2 classes. In one class i have 4 variables. I instantiate another class and use methods which use these variables. I dont want to pass them as parameters. They are set to public. Both classes are in the default package with each other. heres my code:

public class c1 {
     public int x, y, x1, y1;
     public static void main(String args[]) {
          c1 a = new c1();
     }
     public c1() {
          c2 b = new c2();
          b.getSlope();
     }
}

public class c2 {
     public c2() {}
     public int getSlope() {
          return (y-y1)/(x-x1);
     }
}

i get an error which says: cannot find symbol

答案1

得分: 1

你实例化对象(属于一个类)。你的“变量”是该类的字段。如果这些字段不是静态的(与你的代码一样),它们属于对象,你必须将相应的对象传递给另一个类的方法,以访问这些字段。

所以在调用该方法时应该是

b.getSlope(a)

在调用方法时,实现必须具有该参数

 public int getSlope(c1 c) {
      return (c.y-c.y1)/(c.x-c.x1);
 }

如果你希望字段属于类,它们必须是静态的。

(请注意,在Java中,按照约定,类名应该以大写字母开头)。

英文:

You instantiate objects (of a class). Your 'variables' are fields of that class. If the fields are not static (as in your code), they belong to the object and you have to pass the corresponding object to the method of the other class to access the fields.

So it should be

b.getSlope(a)

when calling the method and the implementation has to have that argument

 public int getSlope(c1 c) {
      return (c.y-c.y1)/(c.x-c.x1);
 }

If you like to have the fields belong to the class, they have to be static.

(Note that in Java - by convention - class names should start with a Capital letter).

答案2

得分: 0

变量 x、y、x1、y1 在你的 c2 类中不存在,所以你的代码永远无法编译。

如果你想在 c2 类中使用 x、y、x1 和 y1,请考虑尝试另一种方法。

英文:

Variables x, y, x1, y1 do not exist in your c2 class so your code will never compile.

If you want to use x, y , x1 and y1 in your c2 class, consider trying another method.

huangapple
  • 本文由 发表于 2020年5月30日 23:41:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/62104825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定