2

我想调用一个扩展类的函数。如何才能做到这一点?

class Main{
    Function();
}

class Other extends Main{
    public void Function() { /* The function code */ }
}
4

4 回答 4

2
public class BaseCls {
    void function() {
        System.out.println("Base");
    }
}



public class ExtCls extends BaseCls {
void function() {
    super.function();
    System.out.println("ExtCls");
}

public static void main(String args[]) {
    new ExtCls().function();
    }
} 
于 2012-04-24T16:13:12.277 回答
0

Class Main has no special privileges with regard to what is in Class Other that is not in Class Main. Also, a Main object is not necessarily an Other object. So you need to define the behavior when the an object of Class Main call Function(). You can either

  • Declare Function() to be abstract, meaning you cannot create an object of Class Main and class Other is forced to define Function() or be abstract itself, or
  • Declare a default implementation in Class Main that works for objects that are Mains and not Others.

Either way is acceptable depending on the situation. You have to give more details if you want help choosing which one is better in your situation.

Example:

class Main {
    public abstract void Function();    

    private void SomeFunction() {
        Function();
    }
}

class Other extends Main {
    public void Function() { /* code here */ }

}

or

class Main {
    public void function() { /* default code here, can be empty */ };    

    public void someFunction() {
        function();
    }
}

class Other extends Main {
    public void function() { /* code here */ }

}

class Example {
    public void example() {
        Main main = new Main();
        Other other = new Other();

        main.function(); // call the function defined in class Main
        other.function(); // call the function defined in class Other

        main.someFunction(); // call Main.someFunction, which calls Main.function
        other.someFunction(); // call Main.someFunction, which calls Other.function
    }
}
于 2012-04-24T16:29:22.950 回答
0

可以定义Main为抽象类,也可以定义function()为抽象方法,在Other子类中实现。但是,在某些时候,您必须创建 的实例Other

于 2012-04-24T16:05:17.350 回答
0
class Main {
    public void Function() { F2(); }

    public abstract void F2();
}

class Other extends Main {
    public void F2() { /* code here */ }
}
于 2012-04-24T16:08:15.020 回答