Java class attribute value

I do not understand how this works.

We have two classes A and B. Class B extends A. Class A has an x ​​attribute and a testing method that modify this attribute. Class B has an attribute x and a testing method that modify this attribute.

public class A {

    int x;

    public void test() {
         this.x = 1;
        System.out.println("A" + getX());
    }
    int getX() {return x;}
}

public class B extends A {

    int x;

    public void test() {
        this.x = 2;
        System.out.println("B" + getX());
    }
    int getX() {return x;}

}

public class Main {

    public static void main(String[] args) {

        A a = new A();
        a.test();
        System.out.println(a.getX());

        System.out.println("point 1");
        a = new B();
        a.test();
        System.out.println(a.x);
       }
}

Output:

 A1
 1
 point 1
 B2
 0

My prediction about the last line of output was 2, but equal to 0. Why 0?

+4
source share
4 answers

Explain these lines of code:

a = new B();
a.test();
System.out.println(a.x);
  • You create a new object B. It will reinitialize the variable - A.x = 0and B.x = 0.
  • a.test(), test() B, B.x 2, this.x = 2;. , A.x - 0.
  • A.x, x A. . , . x B x A.
+5

A B x, B , A. int x; B super.x, .

+2

.

A a;

JVM, , -, A.

,

a = A();

JVM, A A

;

a.test();

JVM, A test().

, , :

a = new B();

JVM, B A. , B A .

( A, B).

a.test();

, A B. JVM B, , A.

+2

, /. : "a", "A". , ( B), JVM . , " 1" a.test , "point1" B-. , ( ) . ( a.x), JVM . A. , : ((B)a).x Please note: the difference between the actual and the declared object is based on the type after the "new" operator (for example new B()), and in the declaration of the object

+1
source

Source: https://habr.com/ru/post/1530448/


All Articles