Java ...我正在使用'this'吗?

use*_*844 1 java

遇到问题,我想知道我this是否正确使用.

这个可以吗?

public person{
.
.
.
    public void setmother(person mom){
        mom.addchild(this);
    }
Run Code Online (Sandbox Code Playgroud)

我创造了一个personb班级.在setmother中,我想使用一种方法将子类添加到类中.我想将类的当前实例添加到类的mom实例中的子数组中.

我甚至不知道我的语言是否有所下降...希望有人理解我正在做的事情!

mik*_*era 6

您的代码看起来很好,即您正确使用"this".

设置一个从孩子到母亲的字段可能是一个好主意 - 否则将来很难实现相应的"getMother"方法,例如:

public class Person {
    private Person mother;
.
.
.
    public void setMother(Person mom){
        mom.addChild(this);
        mother=mom;
    }
.
.
}
Run Code Online (Sandbox Code Playgroud)

我要改变的另一个小问题是命名约定,以便更符合通常的Java风格:

  • person => Person(类名以大写字母开头)
  • setmother => setMother(方法名称以小写字母开头,但使用大写字母表示后续单词)
  • addchild => addChild