I am getting some argument errors while compilation. don't know what wrong this.
I was expecting the output would be bj. since Class a doesn't have default constructor so at compilation time default constructor would be created by JVM. and the remaining output would be bj. Am I missing something?
class a
{
a(String b)
{
System.out.println("this is a");
}
}
class b extends a
{
b()
{
System.out.println("b");
}
}
class c extends b
{
c(String j)
{
System.out.println(j);
}
public static void main(String...k)
{
new c("J");
}
}
The error is shown below:
javac construct.java
construct.java:12: error: constructor a in class a cannot be applied to given ty
pes;
{
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
since Class a doesn't have default constructor so at compilation time default constructor would be created by JVM
The default constructor is created only if you don't define a custom constructor .
Your IDE should have shown you the following message on b()
declaration:
There is no default constructor available in ' package .a'
When you tried to instantiate b
, it did an implicit call to super()
but found only a(String b)
instead of a()
. As the error message says, a(String b)
expected a String
but got no arguments.
The solution is either to create the parameterless a()
constructor or call the a(String b)
constructor in class b
constructor.
class b extends a
{
b()
{
super(""); // call to class a constructor passing some string as argument
System.out.println("b");
}
}
By convention you should name Java Classes in upper case letters
When new C("J");
is executed, it calls the constructor of class C
. But as class C
is extending class B
, JVM will add
C(String j)
{
super(); //added by JVM - calls the constructor of super class
System.out.println("j");
}
So the constructor of class b is invoked and as it is also extending class A
.
B()
{
super(); //added by JVM
System.out.println("b");
}
Now problem arises. As JVM will add default constructor in its implicit call. But there is no constructor defined with no-arguments. That's why you are getting an error. You can add super("");
in constructor B to resolve the error or create a constructor with no parameters.
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.