Running into problems and I'm wondering if I'm using this
correctl开发者_StackOverflowy.
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, i.e. 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, i.e. 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
Yes, you are using this
correctly, apart from it not being called "self", and regardless of the other syntax errors in the above code.
精彩评论