为什么Java中的静态方法不能是抽象的? [英] Why can't static methods be abstract in Java?

查看:32
本文介绍了为什么Java中的静态方法不能是抽象的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是在 Java 中为什么我不能定义抽象静态方法?例如

The question is in Java why can't I define an abstract static method? for example

abstract class foo {
    abstract void bar( ); // <-- this is ok
    abstract static void bar2(); //<-- this isn't why?
}

推荐答案

方法的 abstract 注释表明该方法必须在子类中被覆盖.

The abstract annotation to a method indicates that the method MUST be overriden in a subclass.

在 Java 中,static 成员(方法或字段)不能被子类覆盖(在其他面向对象的语言中不一定如此,请参阅 SmallTalk.)static 成员可能被隐藏,但这与覆盖根本不同.

In Java, a static member (method or field) cannot be overridden by subclasses (this is not necessarily true in other object oriented languages, see SmallTalk.) A static member may be hidden, but that is fundamentally different than overridden.

由于不能在子类中覆盖静态成员,因此不能对它们应用 abstract 注释.

Since static members cannot be overriden in a subclass, the abstract annotation cannot be applied to them.

顺便说一句 - 其他语言确实支持静态继承,就像实例继承一样.从语法的角度来看,这些语言通常要求在语句中包含类名.例如,在Java中,假设你在ClassA中编写代码,这些是等价的语句(如果methodA()是静态方法,并且没有具有相同签名的实例方法):

As an aside - other languages do support static inheritance, just like instance inheritance. From a syntax perspective, those languages usually require the class name to be included in the statement. For example, in Java, assuming you are writing code in ClassA, these are equivalent statements (if methodA() is a static method, and there is no instance method with the same signature):

ClassA.methodA();

methodA();

在 SmallTalk 中,类名不是可选的,所以语法是(注意,SmallTalk 没有使用 . 来分隔主语"和动词",而是使用它作为语句终止符):

In SmallTalk, the class name is not optional, so the syntax is (note that SmallTalk does not use the . to separate the "subject" and the "verb", but instead uses it as the statemend terminator):

ClassA methodA.

因为总是需要类名,所以总是可以通过遍历类层次结构来确定方法的正确版本".对于它的价值,我偶尔会错过 static 继承,并且在我第一次开始使用 Java 时被 Java 中缺少静态继承所困扰.此外,SmallTalk 是鸭子类型的(因此不支持按合同编程.)因此,它没有用于类成员的 abstract 修饰符.

Because the class name is always required, the correct "version" of the method can always be determined by traversing the class hierarchy. For what it's worth, I do occasionally miss static inheritance, and was bitten by the lack of static inheritance in Java when I first started with it. Additionally, SmallTalk is duck-typed (and thus doesn't support program-by-contract.) Thus, it has no abstract modifier for class members.

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

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