I am confused about
super.i = j+1;
this line of code. I think it only change the variable i in class A, and dosen't change the inherited variable i in class B.
To make the question clear, I add another sample(sample 2). In sample 2, we use
super(balance,name);
to initialize the attributes inherited from the parent class. When we call super and change the variable balance and name, we don't change the variable balance and name in parent class.
In sample 1, we use
super.i = j+1;
We actually change the variable i in parent class, not the variable i inherited from the parent class. What's the difference between these two samples? Thank you so much.
edited July 18,2019
I have added a diriver class in sample 2. After we create an object c in CheckingAccount, the balance in c is 200 and name is "XYZ". We use super(argument) in subclass, do we change the balance and name in superclass? If not, why the variable i in Sample 1 is changed?
//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);
}
}
The output is
2 3
Here is where i
in class B hides i
in class A. And this.i
and super.i
are different.
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
}
}