关于 java 中的继承

About inheritance in java

我很困惑

super.i = j+1;

这行代码。我认为它只更改 class A 中的变量 i,而不会更改 class B.

中的继承变量 i

为了让问题更清楚,我添加了另一个示例(示例 2)。在示例 2 中,我们使用

super(balance,name);

初始化从父级继承的属性class。当我们调用 super 并更改变量 balance 和 name 时,我们不会更改 parent class 中的变量 balance 和 name。

在示例 1 中,我们使用

super.i = j+1;

我们实际上更改了父class中的变量i,而不是从父class继承的变量i。这两个样本有什么区别?非常感谢。


2019 年 7 月 18 日编辑

我在示例2中添加了一个驱动程序class,我们在CheckingAccount中创建了一个对象c之后,c中的余额为200,名称为"XYZ"。我们在 subclass 中使用 super(argument),我们是否更改 superclass 中的余额和名称? 如果不是,为什么要改变样本1中的变量i?

//Sample one
class A{
    int i;
}

class B extends A{
    int j;
    void display() {
        super.i = j+1;
        System.out.println(j+ " "+i);
    }
}

public class CC {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        B obj = new B();
        obj.i =1;
        obj.j = 2;
        obj.display();
    }

}
//sample 2
//parent class
public class BankAccount {

    protected double balance=0;
    protected String name="ABC";

    public BankAccount(double balance, String name) {
        this.balance = balance;
        this.name = name;
    }
}

//child class

public class CheckingAccount extends BankAccount{
    final int CHARGE = 5;
    final int NO_CHARGE = 0;
    private boolean hasInterest;

    public CheckingAccount(double balance, String name, boolean hasInterest) {
        super(balance,name);
        this.hasInterest = hasInterest;
    }
}

//driver class
public class DriveClass {

    public static void main(String[] args) {
        CheckingAccount c = new CheckingAccount(200,"XYZ",true);
}
}

输出为

2 3

这里是 i in class B 隐藏 i in class A 的地方。this.isuper.i 是不同的。

class A {
   int i;

   void print() {
      System.out.println("i = " + i);
   }
}

class B extends A {
   int j;
   int i;

   void display() {
      i = j + 1;
      super.i = 1000;
      System.out.println(j + " " + i);
      print(); // this will print the i in A
   }
}

super(balance, name)

这调用了父class的构造函数来初始化父class中的变量balance和name。是的,它确实改变了 parent class

中的 balance 和 name 的值

super.i = j+1

这将 j+1 分配给父 class 变量 i。

一种是通过构造函数初始化父class变量,另一种是直接给父class变量赋值。两者不同