我们可以在抽象类中使用静态方法吗? [英] Can we use static method in an abstract class?

查看:627
本文介绍了我们可以在抽象类中使用静态方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java编程中,我们可以调用抽象类的静态方法吗?

是的我知道我们不能将静态方法与抽象类的方法一起使用。但是我想知道为什么..?

In Java Programming, Can we call a static method of an abstract class?
Yes I know we can't use static with a method of an abstract class. but I want to know why.. ?

推荐答案

在Java中,你可以在抽象类中使用静态方法:

In Java you can have a static method in an abstract class:

abstract class Foo {
   static void bar() { }
}

这是允许的,因为即使您没有抽象类的实例,也可以直接调用该方法:

This is allowed because that method can be called directly, even if you do not have an instance of the abstract class:

Foo.bar();

但是,出于同样的原因,您不能声明静态方法是抽象的。通常,编译器可以保证抽象方法在调用它时会有实际的实现,因为您无法创建抽象类的实例。但由于可以直接调用静态方法,因此将其设为抽象可以调用未定义的方法。

However, for the same reason, you can't declare a static method to be abstract. Normally, the compiler can guarantee that an abstract method will have a real implementation any time that it is called, because you can't create an instance of an abstract class. But since a static method can be called directly, making it abstract would make it possible to call an undefined method.

abstract class Foo {
   abstract static void bar();
}

// Calling a method with no body!
Foo.bar();

在界面中,所有方法都是隐式抽象。这就是接口无法声明静态方法的原因。 (没有架构原因,为什么接口不能有静态方法,但我怀疑JLS的编写者认为这会鼓励滥用接口)

In an interface, all methods are implicitly abstract. This is why an interface cannot declare a static method. (There's no architectural reason why an interface couldn't have a static method, but I suspect the writers of the JLS felt that that would encourage misuse of interfaces)

这篇关于我们可以在抽象类中使用静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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