2014-12-05 16 views
0

我在嘗試如下的Java繼承代碼。Java派生的子類對象無法解析符號

class A4 { 
int i, j; 

A4(int a, int b) { 
    i = a; 
    j = b; 
} 

// display i and j 
void show() { 
    System.out.println("i and j: " + i + " " + j); 
} 
} 

class B4 extends A4 { 
int k; 

B4(int a, int b, int c) { 
    super(a, b); 
    k = c; 
} 

// overload show 
void show(String msg) { 
    System.out.println(msg + k); 
} 
} 

class Overload { 
B4 subOb = new B4(1, 2, 3); 

subOb.show("This is k: "); // this calls show() in B4, also cannot resolve symbol 'show` 
subOb.show(); // this calls show() in A4, also cannot resolve symbol `show` 
} 

問題是subOb無法解析,作爲IDE(IntelliJ)夾在代碼示出的兩個錯誤。我想知道代碼有什麼問題以及如何解決問題。

+3

把那些在方法內部。 – 2014-12-05 12:58:35

+0

這些類中包含哪些包?都一樣嗎? – 2014-12-05 13:10:25

回答

1

您使用了錯誤的範圍。

必須在其他方法中調用方法或初始化字段。

你可以做這樣的事情:

class Overload { 
    static B4 subOb = new B4(1, 2, 3); 

    public static void main(String[] args) { 
     subOb.show("This is k: "); // this calls show() in B4, also cannot resolve symbol 'show` 
     subOb.show(); // this calls show() in A4, also cannot resolve symbol `show` 
    } 
} 

或本:

class Overload { 
    B4 subOb = new B4(1, 2, 3); 

    public static void main(String[] args) { 
     Overload obj = new Overload(); 
     obj.doStuff(); 
    } 

    public void doStuff() { 
     subOb.show("This is k: "); // this calls show() in B4, also cannot resolve symbol 'show` 
     subOb.show();    // this calls show() in A4, also cannot resolve symbol `show` 
    } 
} 
1

把一個方法中調用: 試試這個:

class Overload { 
    B4 subOb = new B4(1, 2, 3); 
void overLoad(){ 
    subOb.show("This is k: "); 
    subOb.show(); 
    } 
}