user717572
user717572

Reputation: 3652

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?

Upvotes: 4

Views: 3047

Answers (3)

Averroes
Averroes

Reputation: 4228

You can also do this

   //Vehicle constructor
    public Vehicle() {
        super(Vehicle.class.getSimpleName()); 
    }

    //Plane constructor
    public Plane(){
        super(Plane.class.getSimpleName());
    }

Upvotes: 1

Matt
Matt

Reputation: 11805

As the compiler told you, you can't call instance methods as part of the invocation of the "super()" method.

You can however call static methods. Also, while in the super constructor code itself, you can always call "getClass()" and it will return the actual instance type.

public class A {
  public A() {
      System.out.println("class: " + getClass().getName());
  }
}

public class B extends A {
  public B() {
      super();
  }
}

new A(); --> "class: A"
new B(); --> "class: B"

Upvotes: 0

SLaks
SLaks

Reputation: 887807

You don't need to do that.

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

Upvotes: 8

Related Questions