简体   繁体   中英

Java…am i using 'this' correctly?

Running into problems and I'm wondering if I'm using this correctly.

Is this ok?

public person{
.
.
.
    public void setmother(person mom){
        mom.addchild(this);
    }

I'm created a personb class. Inside setmother, I want to use a method that adds children to the class. I want to add the current instance of the class to the array of children in the mom instance of the class.

I don't even know if I have the lingo down...hopefully someone understands what I'm trying to do!

Your code looks fine as it stands, ie you are using "this" correctly.

It's probably a good idea to also set a field that points from the child to the mother - otherwise it can be hard to implement a corresponding "getMother" method in the future, ie something like:

public class Person {
    private Person mother;
.
.
.
    public void setMother(Person mom){
        mom.addChild(this);
        mother=mom;
    }
.
.
}

The other minor thing I would change is the naming convention in order to be more in line with usual Java style:

  • person => Person (class names start with capitals)
  • setmother => setMother (method names start with lowercase but use capitals for following words)
  • addchild => addChild

是的,除了上面的代码中没有其他语法错误外,您还可以正确地使用this ,除了它不被称为“ self”。

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