【问题标题】:Java - Using an object in a method that's instantiated in another method of the same class [duplicate]Java - 在同一类的另一个方法中实例化的方法中使用对象[重复]
【发布时间】:2023-03-19 05:05:01
【问题描述】:

我对 Java 中对象的范围有疑问。 例如,我有两个类,分别称为 A 类和 B 类。主方法在 A 类中,我在 main() 中实例化了 B 类的一个对象。我发现我不能在 A 类的另一个方法中使用这个对象。这是为什么呢?如果我想在这个类的方法中使用另一个类中的方法,我该怎么做?

public class A 
{
    public static void method()
    {
     int i = example.value;
    } 
    public static void main(String args[])
    {
      B example = new B();
      method();
    }
}
public class B
{
 public int value = 3;
}

我可以这样做吗?

public class A 
{
    static B example;
    public static void method()
    {
     int i = example.value;
    } 
    public static void main(String args[])
    {
      example = new B();
      method();
    }
}
public class B
{
 public int value = 3;
}

【问题讨论】:

  • 范围不适用于对象。它适用于程序源代码中的名称。
  • 另外,一旦method 执行完毕,i 就会被销毁,所以无论如何你都无法访问它。
  • @SotiriosDelimanolis:所以在我上面的例子中,我该如何更改以访问 A 类方法中的 B 类成员?
  • 刷新您的页面。链接的帖子解释了您的选择。
  • 我不明白那个链接的帖子。它只有一个类。我有两个不同的类,想在这个类的方法中使用另一个类的对象?

标签: java class object methods scope


【解决方案1】:

需要将B对象作为参数传递给方法:

public void method(B example)
{
 int i = example.value;
} 
public static void main(String args[])
{
  B example = new B();
  method(example);

【讨论】:

  • 我在上面通过在方法调用之外声明一个静态对象进行了编辑。这会导致任何问题吗?谢谢~
  • 如果你在方法之外声明它,但在同一个类中,你不需要在方法参数中传递它,但它应该可以工作。 Google Java 成员变量。
猜你喜欢
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多