![](/img/trans.png)
[英]Why does the main() method doesn't throw formal and actual parameters mismatch error?
[英]why does this code give error as actual formal parameter?
class A {
int a, b;
A(int i, int j) {
a = i;
b = j;
}
}
class B extends A {
int c, d;
B(int i, int j) {
c = i;
d = j;
}
}
public class HelloWorld {
public static void main(String[] args) {
A aa = new A(5, 6);
B bb = new B(3, 4);
System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);
}
}
它給出錯誤為
HelloWorld.java:9: error: constructor A in class A cannot be applied to given types;
{
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
當類B
擴展類A
,您必須在某處調用要擴展的類的構造函數。
由於類A
沒有沒有參數的構造函數 ,因此您需要顯式調用超級構造函數(類A
的構造函數)作為類B
構造函數內的第一條語句:
B(int i, int j) {
super(i, j);
// Your code
}
如果在A
有一個no-args構造函數,則不需要這樣做,因為如果未指定構造函數調用,則隱式調用no-args構造函數:
B(int i, int j) {
// Your code
}
實際上是在做:
B() {
super();
// Your code
}
由於沒有A()
作為構造函數,因此會出現錯誤。
檢查這一點... JVM總是在尋找沒有參數的構造函數。
class A {
int a, b;
A(int i, int j) {
a = i;
b = j;
}
public A() {
// TODO Auto-generated constructor stub
}
}
class B extends A {
int c, d;
B(int i, int j) {
c = i;
d = j;
}
}
public class pivot {
public static void main(String[] args) {
A aa = new A(5, 6);
B bb = new B(3, 4);
System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.