Java派生的子类对象无法解析符号

时间:2014-12-05 12:52:18

标签: java inheritance intellij-idea multiple-inheritance

我正在尝试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)捕获了代码中显示的两个错误。我想知道代码有什么问题以及如何解决问题。

2 个答案:

答案 0 :(得分:1)

将调用放入方法中: 试试这个:

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

  void overLoad(){
      subOb.show("This is k: ");
      subOb.show();
  }
}

答案 1 :(得分: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`
    }
}