面试题:Java静态/非静态方法重写

1.非静态方法重写

public class Test {
    public static void main(String[] args) throws Exception {
        Tree pine = new Pine();
        Tree oak = new Oak();
        say(pine);
        say(oak);
    }
    private static void say(Tree tr) {
        tr.say();
    }
}

class Tree {
    public void say() {
        System.out.println("Tree");
    }
}
class Pine extends Tree {
    public void say() {
        System.out.println("Pine");
    }
}
class Oak extends Tree {
    public void say() {
        System.out.println("Oak");
    }
}

程序执行后输出:
Pine
Oak

 

2.静态方法重写

class Tree {
    public static void say() {
        System.out.println("Tree");
    }
}
class Pine extends Tree {
    public static void say() {
        System.out.println("Pine");
    }
}
class Oak extends Tree {
    public static void say() {
        System.out.println("Oak");
    }
}

程序执行后输出:
Tree
Tree

 

3.原因分析

静态方法是属于类的,理论上可以重写,但其不具有多态性。因为多态性指在运行时确定类型,静态方法却是在编译时就确定类型的。

多态性只与实例、非静态方法相关。

posted @ 2015-05-11 18:45  快乐的欧阳天美1114  阅读(1329)  评论(1编辑  收藏  举报