Overrides and overloads are for methods, and the variables of subclasses can overwrite the variables of the parent class, but cannot change the parent class's variables.
Class Animals {
int age = ten;
void Enjoy () {
System.out.println ("Animals enjoy!");
}
Class Dogg extends Animals {
int age =;
int weight;
void Enjoy () {
System.out.println ("Dog enjoy!");
}
public class Testduotai {public
static void Main (string[] args) {
Animals a = new Animals ();
A.enjoy ();
System.out.println (a.age);
Dogg d = new Dogg ();
D.enjoy ();
System.out.println (d.age);
Animals D1 = new Dogg ();
D1.enjoy ();
System.out.println (d1.age);
Dogg s = (Dogg) d1;
System.out.println (s.age);
}
Print results:
Animals enjoy!
10
Dog enjoy!
20
Dog enjoy!
10
20
This shows that the variables of the parent class and subclass exist concurrently, even with the same name.
You see a subclass of a variable in a subclass, and in the parent class you see a variable in the parent class.
They are hidden from each other, and methods with the same name are real overrides (Overrides).
such as animals D1 = new Dogg ();
D1 is a animals object and a Dogg object,
When the method is invoked, it is called based on the actual type of the object, and
the actual type is Dogg, so the method of calling the subclass is always invoked.
and access to the member variable is different, it is animals, access to the parent class of the member variable,
transformation to Dogg, the access is the subclass of the member variable.