简体   繁体   中英

What is the wrong with this java code?

I am learning java. The book I'm reading has a question which asks what is wrong with the following code? I have typed the code in NetBeans and I can see the error but why is this error caused and how is it resolved?

The error is highlighted over the code public A(int t) and it says

Constructor B in class B cannot be applied to given types, require int, found no arguments, reason actual and formal arguments lists differ in length.

Here is the code:

public class Test {
    public static void main(String[] args) {
       B b = new B(5);
    }
}

class A extends B {
    public A(int t)  {
        System.out.println("A's constructor is invoked");
    }
}

class B  {
    public B(int k)   {
        System.out.println("B's constructor is invoked");
    }
}

when your super class has an args constructor and doesn't have a no-args constructor you have to explicitly invoke it using a super(args) call from sub-class constructor

class A extends B {
     public A(int t)  {
         super(t);
            System.out.println("A's constructor is invoked");
        }

}

You need to call the constructor of the super class as the first statement in A(int) :

public A(int t)  {
   super(t);
   System.out.println("A's constructor is invoked");
}

Class B has defined constructor, so it does not have public implicit default constructor (with no arguments). All subclass constructors have to explicitly call superclass constructors, via super(t) , if zero argument superclass constructor is not available.

The class B has only one constructor which takes an int argument. On the other hand, the constructor you have in class A (implicitly) tries to call a constructor in A's super class (namely B) that takes no arguments. This is the cause of the error. There are at least two ways to fix the problem:

  1. Create a no-arg constructor in class B.

  2. Explicitly call the constructor in class B which takes an int as a parameter. You can do this using the super keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM