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

class, inheritance, java

Solution

You don't need to do that.

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

Problem

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?

Original source