子类已经覆盖了父类的静态方法,应该运行子类的静态方法才对呀?

本文通过一个Java示例探讨了静态方法在继承中的行为特点,解释了为何子类实例调用静态方法时会执行父类的方法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package hidestatic;
class Base{
void method(){
system.out.println("method of Base");
}
static void staticMethod(){
System.out.println("static method of Base");
}
}
public class Sub extends Base{
void method(){
System.out.println("method of Sub");
}
static void staticMethod(){
System.out.println("static method of Sub");
}

public static void main(String args[]){
Base sub1=new Sub();
sub1.method();
sub1.staticMethod();

Sub sub2=new Sub();
sub2.method();
sub.staticMethod();
}
}

运行结果:method of Sub
static method of Base
method of Sub
static method of Sub


为什么:sub1.staticMethod()的运行结果是:static method of Base ? 按理说,子类已经覆盖父类的静态方法了,应该运行子类的静态方法才对呀,为什么还是调用父类的静态方法?
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值