有没有办法在"重写"功能。
伪:
function a() {print "B"}
function a() {print "C"}
输出:C
答案 0 :(得分:1)
class MyClass {
public void myMethod () {
System.out.println("MyClass");
}
}
class MySubClass extends MyClass {
@Override
public void myMethod () {
System.out.println("MySubClass");
}
public static void main (String[] args) {
MyClass a = new MyClass();
a.myMethod(); // "MyClass"
MySubClass b = new MySubClass();
b.myMethod(); // "MySubClass"
}
}
在此示例中,MySubClass
会覆盖继承的方法myMethod
。
class MyClass {
public void myMethod () {
System.out.println("myMethod");
}
public void myMethod (int i) {
System.out.println(i * 2);
}
public void myMethod (String s) {
System.out.println("Hello, " + s);
}
public static void main (String[] args) {
MyClass a = new MyClass();
a.myMethod(); // "myMethod"
a.myMethod(33); // "66"
a.myMethod("Jeremy") // "Hello, Jeremy"
}
}
在此示例中,MyClass
有多个方法myMethod
的定义,但它们接受不同的参数。
答案 1 :(得分:0)
只需在其子类中重写该方法。
public class Something {
public Something() {
}
public void printHi() {
System.out.println("Hi");
}
}
public class SomethingElse extends Something {
public SomethingElse() {
}
public void printHi() {
System.out.println("I refuse to say hi!");
}
}
Something something = new Something();
something.printHi(); // prints Hi
SomethingElse somethingElse = new SomethingElse();
somethingElse.printHi(); // prints I refuse to say hi!