Java - 覆盖现有功能

时间:2016-01-19 22:43:32

标签: java

有没有办法在"重写"功能。
伪:

function a() {print "B"}
function a() {print "C"}

输出:C

2 个答案:

答案 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!