Calling super()

后端 未结 12 1068
孤独总比滥情好
孤独总比滥情好 2020-12-01 12:24

When do you call super() in Java? I see it in some constructors of the derived class, but isn\'t the constructors for each of the parent class called automatically? Why woul

12条回答
  •  爱一瞬间的悲伤
    2020-12-01 12:42

    When you have a class that extends another class and the father class have no default constructor then you have to use super() in the Son's constructor to call the constructor in the Father Class with the proper arguments like this :

    class A
    {   
        int a; 
        A(int value) 
        {
          this.a=value; 
          System.out.println("A Constructor " + a ); 
        }
    }
    
    class B extends A
    { 
        int b;
        B()
        {
          super(5);
          this.b=10; 
          System.out.println("B Constructor " + b); 
        } 
    
    }
    

    you have to know that yo can't use "super" with "this" if you want to call another constructor in the calss using "this".

提交回复
热议问题