简体   繁体   English

在自己的类中实例化类型

[英]Instantiating a type in its own class

I cannot figure out what is wrong with this code 我无法弄清楚这段代码出了什么问题

class Test {
    int a;
    Test() {
        a=10;
    }

    void new() {
        Test obj1=new Test();
        Test obj2=new Test();
        obj1.a=20;
        obj2.a=30;
    }

    void test(Test obj3,Test obj4) {
        new();
        obj3=obj1;
        obj4=obj2;
    }
}

Please someone explain what exactly is wrong with this code? 请有人解释此代码到底有什么问题?

Many things are wrong. 许多事情是错误的。

For one, new is a reserved keyword, you cannot use it for a method name; 首先, new是一个保留关键字,您不能将其用作方法名称。

Then, in this function: 然后,在此函数中:

void test(Test obj3,Test obj4)
{
    new();
    obj3=obj1;
    obj4=obj2;
}

obj1 and obj2 are not defined. 未定义obj1obj2 One you get out of your " new() method", your obj1 and obj2 references fall out of scope and cannot be reached anymore; 一个脱离“ new()方法”的对象,您的obj1obj2引用不在范围内,无法再访问;

Finally, obj3 and obj4 would not be affected by this test() method, since Java passes parameters by values, not references: 最后, obj3obj4不会受此影响test()方法,因为Java的由值,而不是引用传递参数:

// doesn't work; when the caller returns, victim is still the same
public void changeInt(int victim)
{
    victim = 0;
}

Change your Code to 将您的代码更改为

class Test
{
int a;
Test obj1;
Test obj2;
Test()
{
a=10;
}
void tester()
{
    obj1=new Test();
    obj2=new Test();
    obj1.a=20;
    obj2.a=30;
}
void test(Test obj3,Test obj4)
{
tester();
obj3=obj1;
obj4=obj2;
}
}

And Try to learn about Scope in java and and new is reserved keyword 并尝试了解Java中的Scope和new保留关键字

obj1 and obj2 are invisible inside the test() method. obj1obj2test()方法中不可见。 void new() is illegal method declaration as new is a keyword. void new()是非法的方法声明,因为new是关键字。

  1. You need to declare obj1 and obj2 as instance method or need to pass it somehow to the test() method as parameter. 您需要将obj1obj2声明为实例方法,或者以某种方式将其作为参数传递给test()方法。

  2. Rename the method void new() to something else. 将方法void new()重命名为其他名称。

My suggestions are only to resolve the compilation error . 我的建议仅是解决编译错误。 It doesn't account for the logical errors , if any , in the code. 它不考虑代码中的逻辑错误(如果有)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM