gpt4 book ai didi

java - 继承:Displaying which class inherits which

转载 作者:行者123 更新时间:2023-12-02 12:47:34 25 4
gpt4 key购买 nike

我是Java新手,正在学习继承概念。问题很简单。如果我的一个类继承了其他类的方法,我如何显示它是由 classX 继承的?

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

这是 ClassPname 代码:

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

最终输出为:

I am players name ;Succesfully inherited by

I am players name ;Succesfully inherited by

我想要的输出:

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

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

最佳答案

可以通过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 {

}
}

输出如下:

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

所以这意味着如果你写extends,它有一个显式的父类,但同时java.lang.Object位于层次结构的顶部。因此,如果您的类不使用 extends,则该类默认将 java.lang.Object 作为父类。

关于java - 继承:Displaying which class inherits which,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44700968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com