有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

超级在Java中是什么意思?

我在一篇论文上问了一个问题,问超级在Java中是什么意思? 有四种选择:

  • A-super表示当前实例的内存地址
  • B-super表示当前实例的超级实例的内存地址
  • C-super表示当前实例的超类
  • D-super可以用在main()方法中

我认为答案应该是B,但答案是C,答案是错的还是我的错

我的翻译可能不太准确,你可以自己翻译:

关于超级的的说法正确的是:
A.是指当前对象的内存地址
B是指当前对象的父类对象的内存地址
C是指当前对象的父类
D可以在main()方法中


共 (2) 个答案

  1. # 1 楼答案

    答案是C

    super是Java中的一个关键字,它指的是超类的实例

    在不同的场景中,您可以使用它,例如,当您重写了子类中的同一方法时,调用超类中的方法,如下所示:

    class MyClass {
       public void myMethod() {
           //Do something
       }
    }
    
    public class MySubClass extends MyClass
    
       public void myMethod() {
          super.myMethod(); // It invokes 'myMethod' parent class's implementation
       }
    }
    

    一个有趣的用法是当您想从子类的构造函数调用超类的构造函数时。在这种情况下,它必须是子类构造函数的第一条语句。但是,即使没有明确添加该调用,编译器也会自动添加该调用:

    public class MySubClass extends MyClass {
       public MySubClass() {
           super(); // If you don't add this statement, it will be added by the compiler
       }
    } 
    

    如前所述,在Baeldung有一篇有趣的文章,您可以在那里找到更多的例子:https://www.baeldung.com/java-super

  2. # 2 楼答案

    B - super means the memory address of current instance's super instance.

    I think the answer should be B, but the answer is C, is the answer's wrong or my wrong?

    你错了Marco's answer(以及注释)解释了为什么C是正确的

    B答案不正确/荒谬,原因有二:

    1. (普通)Java程序无法访问内存地址。Java使用引用,在Java1中,事物是根据引用(而不是地址)来指定的

    2. 实例的超级实例是不存在的。实例既是其(最派生的)类的实例,同时也是其所有超类的实例。因此,“超级实例”的地址将与实例本身的地址相同


    I think B can be explained. Doesn't the current instance have an anonymous super instance inside?

    那是不对的。没有“内部”。您的解释基于对对象建模Java如何实现对象类型/类的错误理解

    这样想:一只(真实世界的)猫里面有匿名的哺乳动物吗?不。我的猫咪“Fluffy”是一种哺乳动物,同时她也是一只猫。当我们把猫看作哺乳动物时,我们故意忽略了使它像猫的特征,而只关注(仅仅)哺乳动物的特征

    同样,在Java中:

    public class Mammal {
        ...
    }
    
    public class Cat extends Mammal {
        ...
    }
    
    Mammal thing = new Cat();
    // The 'thing' still refers to a 'Cat', but we can only see the 
    // 'Mammal' characteristics
    
    Cat fluffy = (Cat) thing;
    // But when we look at it via 'fluffy', we can see it's 'Cat'
    // characteristics too.
    
    System.out.println(fluffy == thing);  // prints "true" because they
                                          // refer to the same object.
    

    1-此术语错误可能是由于英语->;中文或中文->;英语翻译问题