Why do this() and super() have to be the first statement in a constructor?

前端 未结 21 1948
北荒
北荒 2020-11-21 23:10

Java requires that if you call this() or super() in a constructor, it must be the first statement. Why?

For example:

public class MyClass {
    publi         


        
21条回答
  •  悲哀的现实
    2020-11-21 23:20

    class C
    {
        int y,z;
    
        C()
        {
            y=10;
        }
    
        C(int x)
        {
            C();
            z=x+y;
            System.out.println(z);
        }
    }
    
    class A
    {
        public static void main(String a[])
        {
            new C(10);
        }
    }
    

    See the example if we are calling the constructor C(int x) then value of z is depend on y if we do not call C() in the first line then it will be the problem for z. z would not be able to get correct value.

提交回复
热议问题