为什么我们说Java中的静态方法不是虚方法? [英] Why do we say that a static method in Java is not a virtual method?

查看:351
本文介绍了为什么我们说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.

根据定义,Java中的每个非静态方法都是默认的虚拟方法最终和私有方法除外。 多态行为无法继承的方法是虚拟方法。

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.

Java中的抽象类只不过是与C ++等效的纯虚方法。

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

为什么我们说Java中的静态方法不是虚方法?即使我们可以覆盖静态方法,因此它可以提供多态性的一些优点,并且Java中的静态方法可以主要使用它的关联类名调用,但也可以使用它来调用它它与 Java 中相关联的类的对象与调用实例方法的方式相同。

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.

推荐答案

无法覆盖静态方法。它们在编译时受到约束。它们多态。即使你试图调用它就好像它是一个实例方法(你不应该做的IMO),它绑定到该表达式的编译时类型,并且完全忽略执行时间值(即使它为null) :

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);

这种行为对读者来说可能非常混乱,这就是为什么至少一些 IDE允许您生成警告或错误,以通过引用访问静态成员。这是Java设计中的一个缺陷,纯粹而简单 - 但它根本不会使静态方法变得虚拟。

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.

这篇关于为什么我们说Java中的静态方法不是虚方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆