java默认方法是不是虚方法,为什么我们说Java中的静态方法不是虚方法?

In object-oriented paradigm, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature to provide the polymorphic behavior.

According to the definition, every non-static method in Java is by default virtual method except final and private methods. The method which cannot be inherited for polymorphic behavior is not a virtual method.

An abstract class in Java is nothing but the pure virtual method equivalent to C++.

Why do we say that a static method in Java is not a virtual method? Even if we can override the static method and consequently it may give some advantages of the polymorphism and also a static method in Java can be invoked mostly with it's associated class name but it is also possible to invoke it using the object of it's associated class in Java in the same way that an instance method is invoked.

解决方案

You can't override static methods. They are bound at compile-time. They are not polymorphic. Even if you try to invoke it as if it were an instance method (which IMO you shouldn't do) it's bound to the compile-time type of that expression, and the execution-time value is completely ignored (even if it's null):

Thread otherThread = null;

otherThread.sleep(1000); // No errors, equivalent to Thread.sleep(1000);

This behaviour can be very confusing for a reader, which is why at least some IDEs allow you to generate warnings or errors for accessing static members "through" a reference. It was a flaw in Java's design, pure and simple - but it doesn't make static methods virtual at all.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值