簡體   English   中英

為什么此代碼給出錯誤作為實際的形式參數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM