If i have a class that creates a new object and passes a refrence to this() to that new object, should i just use this() or should i create a declaration to that class and pass the declaration instead. I cant seem to find a clear example of when i would use each case when passing a handle to a child object.
public class ThisClass {
ThisClass decHandle;
ThisClass someThing = this;
public String decString = "some string";
SomeOtherClass classObject1 = new SomeOtherClass(this);
SomeOtherClass classObject2 = new SomeOtherClass(decHandle);
SomeOtherClass classObject3 = new SomeOtherClass(someThing);
}
public class SomeOtherClass {
ThisClass decHandle;
public SomeOtherClass (ThisClass handle){
decHandle = handle;
}
String valueForOther = decHandle.someThing;
}
I mostly need to know which is the best practice when passing handles to a child class from the parent.
There are quite a few mistakes here.
1) The last statement in SomeOtherClass should be
instead of
2) When you say
it will throw a NullPointerException, because you have not yet constructed the object. “this” refers to the current object. In your code, there is no object, therefore this line will throw an exception. The same applies to the next line.
3) “Child” means that the class inherits from a parent. Just because SomeOtherClass has a reference to ThisClass, it doesn’t mean that SomeOtherClass is a child.
4) It’s not a good practice to let a class’ members have public visibility.
Ok, so here’s how you would do it.