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:
是的,除了上面的代码中没有其他语法错误外,您还可以正确地使用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.