Java constructor inheritance?

前端 未结 7 2028
一生所求
一生所求 2020-12-15 10:26

I always thought that constructors aren\'t inherited, but look at this code:

class Parent {
    Parent() {
        S         


        
7条回答
  •  忘掉有多难
    2020-12-15 11:03

    public class HelloWorld{
    
        private static class A {
            A(String x) {
                System.out.println(x);
            }
        }
        
        private static class B extends A {
            
        }
    
        public static void main(String []args){
            B b =  new B();
            System.out.println("Hello World");
        }
    }
    

    Output:

    /*
    error: constructor A in class A cannot be applied to given types;
        private static class B extends A {
                       ^
      required: String
      found: no arguments
      reason: actual and formal argument lists differ in length
    1 error
    */
    

    So what it means is constructors are never inherited

    Hence, what happens here is class B's argument less constructor tries to call class A's argument less contructor, But it didn't find that hence gives it gives error.

    If we add argument less constructor in class A, then this program will work properly.

提交回复
热议问题