0

I am new to Java and was learning inheritance concept.The question is very simple. If one of my class inherits a method from other how can I display that it was inherited by classX?

public class class1 extends ClassPname {
    public static void main (String[] args){
        className obj3=new className();
        class1 obj2=new class1();
        obj3.Name();
        obj2.Name();
    }
}

This is the ClassPname code:

public class ClassPname {
    public void Name(){
        System.out.println("I am players name ;Succesfully inherited  by ");
    }
}

The final output is:

I am players name ;Succesfully inherited by

I am players name ;Succesfully inherited by

My desired output :

I am players name ;Succesfully inherited by(class that inherits this)

I am players name ;Succesfully inherited by (Class that inherits this)

nikita_pavlenko
  • 658
  • 3
  • 11
AnishDhoni
  • 37
  • 1
  • 7
  • Use: [`Class.getName()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getName%28%29) – Blasanka Jun 22 '17 at 13:37
  • Also [https://stackoverflow.com/questions/5679254/all-super-classes-of-a-class](https://stackoverflow.com/questions/5679254/all-super-classes-of-a-class) – domsson Jun 22 '17 at 13:37
  • thanks @domdom but the answer got me more confused..Now its cleared..thanks a lot. – AnishDhoni Jun 22 '17 at 13:43

1 Answers1

1

It can be easily taken by getClass().getSuperclass()

public class DemoApplication {

    public static void main(String[] args) {
        Class<?> superclassOfB = new B().getClass().getSuperclass();
        Class<?> superclassOfA = new A().getClass().getSuperclass();
        System.out.println(superclassOfB);
        System.out.println(superclassOfA);
    }

    static class A {

    }

    static class B extends A {

    }
}

The output is following:

class com.example.demo.DemoApplication$A
class java.lang.Object

So it means if you write extends it has an explicit parent class, but at the same time in the top of hierarchy java.lang.Object is located. So if you don't use extends for you class this class has java.lang.Object as a parent class by default.

nikita_pavlenko
  • 658
  • 3
  • 11