【问题标题】:Assign parent 's instance variable by using super keyword in Java在 Java 中使用 super 关键字分配父实例变量
【发布时间】:2023-02-15 20:50:51
【问题描述】:

我有 2 个 Java 课程

1. public class A {
2.     public int i = 1;
3. }
4. 
5. public class B extends A {
6.     int i = 2;
7.     public void print() {
8.         super.i = 3;
9.         A obj = new B();
10.        System.out.println(obj.i);
11.        System.out.println(this.i);
12.        System.out.println(super.i);
13.    }
14.
15.    public static void main(String [] args) {
16.        new B().print();
17.    }
18.}

当我运行上面的代码时,它会打印

1
2
3

所以我想知道为什么第 10 行和第 12 行打印不同的输出?我认为因为我分配了 super.i = 3 并创建了 A 的新对象,所以结果应该是 3、2、3。请帮助我

【问题讨论】:

  • super 引用 this 实例,作为其超类的实例。 objthis 是不同的对象。

标签: java inheritance super


【解决方案1】:

在您的程序中有两个 B 对象,一个由 main() 创建,另一个由第一个对象中的 print() 方法创建。

每个B 都有自己的i 实例。

只有第一个Bi设置为3,而obj指的是第二个B

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2015-10-28
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多