Java: A value problem with inherited variables

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.