为何要在my_method()中实例化子类?主方法已实例化是否重复?
为什么在
my_method()里重复实例化Sub_class? 嘿,这个问题问得特别好!咱们先把你的代码格式化清楚,再一步步拆解:
class Super_class { int num = 20; // display method of superclass public void display() { System.out.println("This is the display method of superclass"); } } public class Sub_class extends Super_class { int num = 10; // display method of sub class public void display() { System.out.println("This is the display method of subclass"); } public void my_method() { // Instantiating subclass - why do you have to do this? Sub_class sub = new Sub_class(); // Invoking the display() method of sub class sub.display(); // Invoking the display() method of superclass super.display(); // printing the value of variable num of subclass System.out.println("value of the variable named num in sub class:"+ sub.num); // printing the value of variable num of superclass System.out.println("value of the variable named num in super class:"+ super.num); } public static void main(String args[]) { Sub_class obj = new Sub_class(); obj.my_method(); } }
核心结论:这里的重复实例化完全是不必要的,属于教学演示的冗余写法!
咱们来拆解原因:
- 首先,
my_method()是Sub_class的实例方法——调用它的obj本身就是一个Sub_class对象。你完全可以直接用当前对象(this)来访问子类的成员,根本不需要再new一个新的Sub_class实例。
比如,你可以把my_method()改成更简洁的版本,效果完全一样:
public void my_method() { // 直接调用子类的display(),等价于this.display() display(); // 调用父类的display() super.display(); // 访问当前对象的子类num,等价于this.num System.out.println("value of the variable named num in sub class:"+ num); // 访问父类的num System.out.println("value of the variable named num in super class:"+ super.num); }
那原代码为什么要多此一举?
这么写的目的大概率是为了直观对比两种访问方式:
- 一边用新的子类实例(
sub)访问子类成员,一边用super访问父类成员,以此演示Java继承里的两个关键特性:- 方法重写(Method Overriding):子类的
display()覆盖了父类的同名方法,无论是用当前对象还是新的子类实例调用,都会执行子类的版本;只有用super.display()才会触发父类的方法。 - 成员隐藏(Member Hiding):子类的
num变量隐藏了父类的同名变量,直接访问num或者用子类实例访问sub.num,取的都是子类的值;只有super.num能拿到父类的变量。
- 方法重写(Method Overriding):子类的
这种写法是为了教学时把概念拆解得更直白,但在实际开发中完全没必要,属于冗余代码。
内容的提问来源于stack exchange,提问作者Isabel
相关产品推荐
相关产品推荐

