Instance variable inheritance in java

class Weather{
    int humidity;
    //default value is 0;
}

class Rainy extends Weather{



    void changeHumidity(){
        humidity = 10;
        System.out.println("The humidity is " + super.humidity);
    }


}

public class Test{
    public static void main(String[] args){
        new Rainy().changeHumidity();
        System.out.println(new Weather().humidity);
    }
}

      

Here output: Humidity 10 and 0

why super.humidity returns 10.I know the instance variable is not inherited, but they can be accessed in the subclass. If they can be accessed in the subclass, does that mean that they are allocated between the superclass and the subclass, or that both the superclass and the subclass have a different copy. Now comes to the question why super.humidity returns 10, but on the next line it returns 0. Finally, make my concept clear.

0


source to share


3 answers


Each copy Weather

and Rainy

has its own copy humidity

.

In your method changeHumidity()

, you referred to as humidity

, and on super.humidity

. They refer to the same instance variable. When you create a new one Rainy

, it inherits everything from Weather

, so you can use it humidity

first.

However, when creating a new Weather

one that has absolutely nothing to do with your instance Rainy

. Let's say we have two objects:



Rainy rainy = new Rainy();
Weather weather = new Weather();

      

Each of the above objects has its own copy humidity

. A change in humidity on the specimen Rainy

does not change the humidity on the specimen Weather

.

rainy.humidity = 20;

System.out.println(weather.humidity); //-> 0

      

+2


source


The Rainy class does not have a Humidity field , so this class uses the parent class field to initialize



if you decrease the moisture field when you change the child class, but print the parent field of the class

+2


source


humidity

is an instance variable.

Instance variables:

These variables refer to an instance of a class, thus an object. And also each instance of this class (object) has its own copy of this variable. Changes made to a variable are not reflected in other instances of this class.

new Weather()

will create a new instance

public class Test{

   int x = 5;

 }

Test t1 = new Test();   
Test t2 = new Test();

      

t1.x=10

will not make any changes to t2.x

. t2.x

will still be 5

0


source