'How to make sure a superclass object is not null
I have two classes, one being the subclass of another. I want to make it so that the superclass can do its original methods even if the actual object is an instance of the subclass.
The below code prints hello null and then outputs the error: Cannot invoke "A.doThis()" because "this.object" is null
public class A {
A object;
public void doSomething(){
System.out.println("hello " + object);
object.doThis();
}
public void doThis(){
System.out.println("Did this");
}
}
public class B extends A{
B object;
public static void main(String[] args){
B b = new B();
b.create();
}
public void create(){
object = new B();
object.doSomething();
}
}
I understand that in Class A, the object is not actually created anywhere which is why it's probably null. I am wondering how can I make it so it's not.
Solution 1:[1]
If you want to reference an instance of the class within one of its methods, then use this.
If you want to make sure that a method in a super class keeps its original implementation and is never overridden by a subclass, then make it final.
If this isn't what you want, then I don't think what you are trying to do is actually practical.
public class A {
public final void doSomething(){
System.out.println("hello " + this);
this.doThis();
}
public final void doThis(){
System.out.println("Did this");
}
}
public class B extends A{
public static void main(String[] args){
B b = new B();
b.create();
}
public void create(){
this.doSomething();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Leo Aso |
