Java - 在同一个类的另一个方法中实例化的方法中使用对象

时间:2015-11-14 02:15:07

标签: java class object methods scope

我对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;
}

1 个答案:

答案 0 :(得分:0)

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

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