如何理解java中的super [英] how to understand super in java
问题描述
遇到一个让我困惑的问题,是关键字'super',我的测试代码是这样的:
I encountered a problem that confused me, it is the keyword 'super', my test code is like this:
package test;
public class Parent {
private String name;
public Parent(){
this.name = "parent";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void showName(){
System.out.println(this.name);
}
}
public class Child extends Parent{
public Child(){
this.setName("Child");
}
public void showName(){
System.out.println(super.getClass().toString());
System.out.println(super.toString());
super.showName();
System.out.println(super.getName());
}
}
public class Test {
public static void main(String[] args) {
Child d = new Child();
d.showName();
}
}
所以结果是这样的:
class test.Child
test.Child@2207d8bb
Child
Child
我对'super'的理解是它是对当前实例的父实例的引用,所以我期望的输出就像'Parent',从结果来看,我错了,就像当前实例调用父方法一样,并且超级"不是父实例,我的理解对吗?有没有办法让父实例只初始化子类?
my understanding about 'super' is that it is a reference to the parent instance of current instance, so my expecting output is like 'Parent', from the result , I am wrong, its like the current instance calls the parent method, and 'super' is not parent instance, is my understanding right ? and is there a way that I can get parent instance only initializing the Child class ?
推荐答案
我对'super'的理解是它是对当前实例的父实例的引用
my understanding about 'super' is that it is a reference to the parent instance of current instance
不 - 没有父实例"这样的东西.当你创建一个实例时,只会创建一个对象——一个Child
的实例,它也继承了Parent
的所有字段和方法.
No - there's no such thing as a "parent instance". When you create an instance, there's only one object created - an instance of Child
, which inherits all the fields and methods from Parent
as well.
super
有两种使用方式:
- 引用方法的超类实现,通常是在您覆盖子类中的方法时.这就是您在
Child.showName
中所做的 - 它正在调用Parent.showName
,但是 在同一个实例上(因为有 是只有一个实例) - 从子类构造函数调用超类构造函数
- To refer to the superclass implementation of a method, typically when you've overridden the method in the subclass. This is what you're doing in
Child.showName
- it's callingParent.showName
, but on the same instance (because there is only one instance) - To call a superclass constructor from a subclass constructor
这篇关于如何理解java中的super的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!