我想调用一个扩展类的函数。如何才能做到这一点?
class Main{
Function();
}
class Other extends Main{
public void Function() { /* The function code */ }
}
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();
}
}
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
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, orMain
that works for objects that are Main
s and not Other
s.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
}
}
可以定义Main
为抽象类,也可以定义function()
为抽象方法,在Other
子类中实现。但是,在某些时候,您必须创建 的实例Other
。
class Main {
public void Function() { F2(); }
public abstract void F2();
}
class Other extends Main {
public void F2() { /* code here */ }
}