1. In Java, if the subclass inherits the static variable of the parent class, the static variable of the parent class will change when you modify the value of the static variable in front of the child class.
Case:
Parent class
public class Animal {
Static properties
public static int age=1;
};
Sub-class
public class Cat extends animal{
Static methods
public static void print () {
System.out.println ("Animal:" +animal.age+ "; Cat: "+cat.age);
};
Common methods
public void Say () {
System.out.println ("Animal:" +animal.age+ "; Cat: "+cat.age);
};
};
Test:
public class Numbermain {
public static void Main (string[] args) {
Cat c=new Cat ();
C.say ();
Cat.print ();
System.out.println ("After Change:");
cat.age=5;
C.say ();
C.print ();
}
};
2. Question: What if the subclass inherits the variables of the parent class? Will the value of the parent class change when this subclass variable is modified?
Case:
Parent class
public class Animal {
public int height=1;
};
Sub-class
public class Cat extends animal{
public int height=1;
public void setheight (int _h) {
This.height=_h;
};
public int getheight () {
return height;
}
public void Say () {
The value of the child class
Animal a=new Animal ();
System.out.println ("Animal class:" +a.height+ "; Cat class: "+this.height);
};
};
Test:
public class Numbermain {
public static void Main (string[] args) {
Cat c=new Cat ();
SYSTEM.OUT.PRINTLN ("No Modification Before:");
C.say ();
SYSTEM.OUT.PRINTLN ("Not modified:");
C.setheight (5);
C.say ();
}
};
Results:
Not modified before:
Animal class: 1; Cat class: 1
After the changes have been
Animal class: 1; Cat class: 5
This shows: When you change the normal variables of the parent class, the variables of the subclass do not change, but if it is a static variable, the value of the subclass static variable will change once the parent class static variable value is modified.
Java: A value problem with inherited variables