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

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

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() 找不到符号。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值