Java静态方法笔记

Java中的静态方法只能继承,不能重写!!

官方文档是这样写的:

Class methods


If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.

如果一个子类定义了一个和父类静态方法中相同的方法(即方法名,参数和返回类型相同),则该类隐藏了父类中的这个方法。

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass

而该隐藏的静态方法是否被调用,取决于是父类(引用)还是子类(引用)调用了该静态方法


以下是一个例子:
public class Test2
{
public static void main(String[] args)
{

//需要注意的是,这里跟以往的父类引用指向子类对象有点不用


//这个子类创建的对象是由子类类型“N”引用的,所以调用output方法将输出“N”


N n = new N();
n.output();

//这个子类创建的对象是由父类类型“M”引用的,所以调用output方法将输出“M”
M m = new N();
m.output();
}

}

class M
{
public static void output()
{
System.out.println("M");
}
}

class N extends M
{
public static void output()
{
System.out.println("N");
}
}


上述例子中如果N类中的output方法没有static修饰,则会报不能重写的编译错,所以static可以这样来解释:加上static是隐藏了父类中的方法,而不是重写。

同样的,如果父类中的方法不是静态的,那么子类中的同名方法也不可以是静态的,也就是说静态的方法不能被覆盖,静态的方法也不能覆盖非静态的,总之一句话:静态的都不能覆盖,要么全静态,要么全非静态。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值