Which constructor initializes the x3 variable?

I found a similar question, but I'm not sure if the answer is correct. I had this question in a Java exam.

Which constructor initializes the x3 variable?

class X {
    int x1, x2, x3;
}

class Y extends X {
    int y1;
    Y() {
        x1 = 1;
        x2 = 2;
        y1 = 10;
    }
}

class Z extends Y {
    int z1;
    Z() {
        x1 = 3;
        y1 = 20;
        z1 = 100;
    }
}

public class Test3 {
    public static void main(String[] args) {
        Z obj = new Z();
        System.out.println(obj.x3 + ", " + obj.y1 + ", " +obj.z1);
    }
}

Answers:

  • A. Only the default constructor of class X
  • B. Only a constructor without class Y arguments
  • C. Only a constructor without an argument of class Z
  • D. Only the default constructor of an object class

Thank you for your help.

+4
source share
3 answers

A subclass inherits all the fields of its superclass. Therefore, when a subclass constructor initializes class properties, inherited superclass properties must also be initialized. To ensure this, the subclass constructor first calls the superclass constructor, and then continues with its own constructor.

Z extends Y Y extends X, new Z() Z(), Y(), X(). X()? java, , no-argument . , X X(). x1, x2 x3 , 0.

, main Z(), Z() Y() Y() X(). X() x3.

+4

, :

, "D" , . x3. , . "X". , - . , Object . , VM.

, , :

class A {
    A() { printMember(); }

    void printMember() {}
}

class B extends A {
    private int x;

    @Override
    void printMember() { System.out.println(x); }
}

public class TestAssignment {
    @org.junit.Test
    public void createInstance() { new B(); }
}

, , "0" - B, "0". , A B. , A., B. C. D.

+2

, Z, X, X Z, Y, Y X no Z.

X, x1 = 0, x2 = 0 x3 = 0, X.

no Y x1 = 1, x2 = 2 y1 = 10.

When initializing the argument constructor no of class Z, it assigns x1 = 3, y1 = 20, and z1 = 100.

So, here answar will be a variant of A ie Only the default constructor of class X.

+2
source

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


All Articles