Home > Software engineering >  In this Java example, why is the first output 84?
In this Java example, why is the first output 84?

Time:07-31

I was studying and I have this code right here:

class A{
    String message = "72";
    static int value = 20;
    public A(){
        message  ="20";
        value *=2;
    }
    boolean equals(A obj){
        return this.method()==obj.method();
    }
    public int method(){
        return 10;
    }
}
class B extends A{
    String message = "452";
    static{
        value  =1;
    }
    public B(){
        message  = "935";
    }
    public int method(){
        return 20;
    }
}

public class C {
    public static void main(String[] args){
        A x = new B();
        B y = new B();
        System.out.println(A.value);
        System.out.println(x.message);
        System.out.println(x==y);
        System.out.println(x.equals(y));
        System.out.println(x.method()   y.method());
        System.out.println(x.getClass().getName());
    }
}

Intellij tells me this is the output: 84 7220 false true 40 B

I understand most of these but I can't understand why the first one is 84. Could anybody explain?

CodePudding user response:

When B is first created, value is set to value 1. Then, each time an A is created -- including a B -- it doubles. (20 1) * 2 * 2 is 84.

CodePudding user response:

Sure)You need to understand this:

  • Whenever you instantiate a child (any instance of B) before executing child constructor, the parent constructor is executed (constructor of A in this case).
  • the static block inside B is a static initialiser. it gets executed only one time when class is loaded Static Block in Java

Therefore when you start executing main A.value = 21. After first line

A x = new B();

A.value becomes 2 * 21 = 42

After the second line

B y = new B();

it follows the same pattern and A.value => 42 * 2 = 84

  • Related