Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call the Super Constructor and pass the Class name in java?

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?

like image 575
user717572 Avatar asked Jan 16 '23 11:01

user717572


1 Answers

You don't need to do that.

You can just call getClass().getSimpleName() directly from the base constructor.

like image 113
SLaks Avatar answered Jan 30 '23 22:01

SLaks