从另一个类访问对象初始化

时间:2022-09-25 10:10:47

So I want to be able to use objects in the main class through starting a method from another class. I have this so far. Can anyone tell me what I'm doing wrong or if its possible in another way?

所以我希望能够通过从另一个类启动一个方法来在主类中使用对象。到目前为止我有这个。任何人都可以告诉我我做错了什么或者其他方式可能吗?

main.java

main.java

public class main extends index {

    public static void main(String []args) {
        index();
        System.out.print(object1.getVal1);
    }
}

index.java

index.java

public class index {

    public static void index() {
        list object1 = new list(val1, val2);
    }

list.java

list.java

public class list {

    //constructors
    private static int val1;
    private static int val2;

    public list(val1, val2) {
        this.setVal1(val1);
        this.setVal2(val2);
        //setters and getters look like this for both val1 and val2

        public static int getVal1() {
            return val1;
        }

        public void setVal1(int val1) {
            this.val1 = val;
        }
    }

1 个解决方案

#1


0  

im also a novice programmer , if i can suggest you, better you assign a variable as result from the invoked method . for example ,

我也是一个新手程序员,如果我可以建议你,最好从调用的方法中分配一个变量作为结果。例如 ,

private bool a;

which then u can assign a as true or false when event triggered returns value that u want .

然后,当事件触发返回您想要的值时,您可以将其指定为true或false。

 a = object1.getVal1(#passing param whatever u want);

then u can print the value directly

然后你可以直接打印这个值

  System.out.println(a);

Hope this helps you.

希望这对你有所帮助。

#1


0  

im also a novice programmer , if i can suggest you, better you assign a variable as result from the invoked method . for example ,

我也是一个新手程序员,如果我可以建议你,最好从调用的方法中分配一个变量作为结果。例如 ,

private bool a;

which then u can assign a as true or false when event triggered returns value that u want .

然后,当事件触发返回您想要的值时,您可以将其指定为true或false。

 a = object1.getVal1(#passing param whatever u want);

then u can print the value directly

然后你可以直接打印这个值

  System.out.println(a);

Hope this helps you.

希望这对你有所帮助。