I have the super class Vehicle
, with it's subclasses Plane
and Car
. The vehicle extends from a class which has a final string name;
field, which can only be set from the constructor.
I want to set this field to the class' name, so the name of Car would be Car, Plane would be Plane and Vehicle would be Vehicle. First thing I thought:
public Vehicle() {
super(getClass().getSimpleName()); //returns Car, Plane or Vehicle (Subclass' name)
}
But this gives me the error: Cannot refer to an instance method while explicitly invoking a constructor
.
How can I still set the name
field to the class name, without manually passing it in as a String?
You don't need to do that.
You can just call getClass().getSimpleName()
directly from the base constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With