简体   繁体   English

如何将对象分配给“this.”?

[英]how can I assign an object to "this."?

代码

Im trying to assign the object to "this.theOctalNumber" but I do not know how.我试图将对象分配给“this.theOctalNumber”,但我不知道如何。 I tried googling but cant find any.我试过谷歌搜索,但找不到任何。

this is representing the current object of this class. this代表这个类的当前对象。

you wanted is this.theOctalNumber , you should add theOctalNumber to class field , not in construction.你想要的是this.theOctalNumber ,你应该将theOctalNumber添加到class field ,而不是在构造中。

OctalNumber theOctalNumber;

public NumberController() {
    this.theOctalNumber = new OctalNumber();

You could also just say你也可以说

class NumberController {

    private OctalNumber theOctalNumber = new OctalNumber();

You don't actually need a constructor to accomplish that.你实际上并不需要一个构造函数来完成它。

The important takeaway though is that if you want to access this.theOctalNumber , you need to declare theOctalNumber as an object field.但重要的一点是,如果你想访问this.theOctalNumber ,你需要将theOctalNumber声明为一个对象字段。 Ie outside any method but inside the class.即在任何方法之外,但在类内。

Incidentally, in Java, you generally don't need the this.顺便说一句,在 Java 中,您通常不需要this. unless you've also declared a local variable or method parameter with the same name.除非您还声明了同名的局部变量或方法参数。 The compiler will automatically fall back to the object field if neither of those is available.如果两者都不可用,编译器将自动回退到对象字段。

There is more about this in the Java Tutorials . Java 教程中有更多关于此的内容。

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

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