首页 > 解决方案 > 如何检索对象

问题描述

在中Class2,我想检索objects(obj1,2)在 init 类中传递的方法变量。但我总是0Class2. 请建议如何obj1,2Class2. 谢谢!

public class Class1 {
    public int Value;

    public void setMethod(int val) {
        this.Value = val;
    }

    public int getMethod() {
        return Value;
    }
}

//initialization class
import Class1;

public class init {
    Class1 obj1 = new Class1();
    Class1 obj2 = new Class1();
    obj1.setMethod(10);
    obj2.setMethod(20);
    System.out.println("obj1 value is" + obj1.getMethod()); // it will print 10
    System.out.println("obj2 value is" + obj2.getMethod()); // it will print 20
}

//another class where I want my obj1, obj2 method variables to retrieve
import Class1;

private class Class2 {
    Class1 obj1 = new Class1();
    System.out.println("obj1 value is" + obj1.getMethod()); // it is printing 0           
}

标签: java

解决方案


您正在尝试从init类中读取对象 1 和 2,但您已经Class1Class2代码中创建了对象。

您的代码中存在编译错误,并且您没有遵循类和方法的正确命名约定。

请参阅下面的代码,您需要使用公共访问修饰符定义三个单独的类。所有对象初始化都可以在类构造函数中完成,或者您可以定义任何公共方法

public class Class1{
  public int value;
  /*public void setMethod(int val){this.Value=val; -- here variable name is in small letter so compiler error}
  public int getMethod(){return Value;  -- here variable name is in small letter so compiler error}  -- getter setter name is not correct*/

 public void setValue(int val) {this.value=val;}
 public int getValue(){return this.value;}
}    

public class Init{
    Class1 obj1 = new Class1();
    Class1 obj2 = new Class1();

    public Init() {
        obj1.setValue(10);
        obj2.setValue(20);
        System.out.println("obj1 value is"+obj1.getValue()); // it will print 10
        System.out.println("obj2 value is"+obj2.getValue()); // it will print 20        
    }
}

public class Class2{
/*  Class1 obj1 = new Class1(); -- here obj1 will not refer to object in Init class
System.out.println("obj1 value is"+obj1.getMethod()); // it is printing 0           */
    public static void main(String[] args) {
        Init init = new Init();
        Class1 obj1 = init.obj1;  
        System.out.println("obj1 value is"+obj1.getValue());// this will print 10       
    }
}

推荐阅读