简体   繁体   中英

how can I assign an object to "this."?

代码

Im trying to assign the object to "this.theOctalNumber" but I do not know how. I tried googling but cant find any.

this is representing the current object of this class.

you wanted is this.theOctalNumber , you should add theOctalNumber to class field , not in construction.

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. Ie outside any method but inside the class.

Incidentally, in Java, you generally don't need the 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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