在java中我们不能覆盖最终方法但是可以重载吗?
是的,重载最终方法是完全合法的.
例如:
public final void doStuff(int x) { ... } public final void doStuff(double x) { ... }
是的,但请注意,动态调度可能无法达到预期效果!快速举例:
class Base { public final void doSomething(Object o) { System.out.println("Object"); } } class Derived extends Base { public void doSomething(Integer i) { System.out.println("Int"); } } public static void main(String[] args) { Base b = new Base(); Base d = new Derived(); b.doSomething(new Integer(0)); d.doSomething(new Integer(0)); }
这将打印:
Object Object
是的,非常有可能.
一个小程序来演示它:
class A{ final void foo(){ System.out.println("foo ver 1 from class A"); } final void foo(int a){ System.out.println("foo ver 2 from class A"); } } class B extends A{ final void foo(long l){ System.out.println("foo ver 3 from class B"); } // final void foo(){ System.out.println("foo ver 1 from class A"); } NOT ALLOWED } public class Test { public static void main(String [] args){ B obj = new B(); obj.foo(); obj.foo(1); obj.foo(1L); } }
输出:
foo ver 1 from class A foo ver 2 from class A foo ver 3 from class B