(java)父类的静态方法为子类覆盖后,丢失多态性的问题

来源:互联网 发布:淘宝 刷单 没有权重 编辑:程序博客网 时间:2024/06/05 14:13

在继承机制中,类的静态方法只能被子类的静态方法覆盖,且覆盖以后没有多态(访问的是父类的静态方法);
示例程序:

class StaticTest1{    private static int c=2017;    public static void print(){        System.out.println(c+" is a different year!");    }}public class Statictest extends StaticTest1{    private static int c=2018;    public static void print(){        System.out.println(c+" will be a good year!");    }    public static void main(String[] args)     {        StaticTest1 s=new Statictest();        s.print();    }}/*Output:2017 is a different year!*/

若print()方法为非静态方法, 输出的肯定是:“2018 will be a good year!”了。
在下面的程序中将会出现错误:

class StaticTest1{    private static int c=2017;    /*public static void print(){        System.out.println(c+" is a different year!");    }*/}public class Statictest extends StaticTest1{    private static int c=2018;    public static void print(){        System.out.println(c+" will be a good year!");    }    public static void main(String[] args)     {        StaticTest1 s=new Statictest();        s.print();    }}

错误提示是:s.print() 找不到符号。

阅读全文
0 0
原创粉丝点击