Shady Atef
Shady Atef

Reputation: 2401

Is there a way to get class name using inherited superclass method?

Assume I have two classes

class A {
public static String getMyClassname()
 {
    // return the class name it was called on
 }
}


class B extends A{}

Is there any utility in java that allows me if I call A.getMyClassname() I'd get A and if i call B.getMyClassname(), I'd get B ?

Upvotes: 0

Views: 92

Answers (2)

R.Costa
R.Costa

Reputation: 1393

Yes, if you make the method non-static

class A {

    public String getMyClassname() {
        return this.getClass().getSimpleName();
    }
}


class B extends A {}

You can then do

A a = new A();
B b = new B();

System.out.println(a.getMyClassname());
System.out.println(b.getMyClassname());

Output

A
B

Upvotes: 0

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

Why use static ? Just override that function without using static and then do your method call.

Something like this :

class A {
   public String getMyClassname()
     {
       return "A"
     }
 }


  class B extends A {
   @override
   public String getMyClassname()
     {
       return "B"
     }
 }

Upvotes: 1

Related Questions