我们可以将超类声明为静态类吗?如果不是为什么? [英] can we declare a super class as static one? if not why?

查看:72
本文介绍了我们可以将超类声明为静态类吗?如果不是为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以将超类声明为静态吗?

can we declare a super class as static one?

推荐答案

不,你不能从静态类派生一个类(只能嵌套在Java中) 。但为什么不呢?



严格来说,这是一种自愿的决定。简短的回答是:这是因为Java的作者技术就是这样设计的。但是,Java静态类背后的一个理性点是它们无法实例化。在这种情况下,继承的作用将非常有限。



很有可能在静态类上创建一些带有继承的OOP技术。但是您需要决定如何解释继承的静态成员。每个这样的成员都是整个类的成员,而不是实例。也许如果你有 A 类的成员 AM ,你可能想要得到两个M新类 B 来自 A AM BM ,否则你可以踩到同一个对象。它有多大意义吗?这可能取决于您的技术的其他功能。



这在实践中并不是一个相当大的限制。我可以告诉你如何从静态类派生。只需创建一些只有静态成员的类,但不要将关键字 static 添加到类本身。你将获得静态而不是正式的类,但只有 de-facto 。您使用此类作为基类,从中派生另一个类。这种事实上的静态类与真实的静态类没有任何功能或性能/内存差异。但由于这两个类只有静态成员,因此不会给你太多。你只能为同一个成员命名一种别名。 (与前一段中描述的想法相反,您的 AM BM 将是同一个对象



为什么能够将真正的静态类用作基类呢?它还会添加一个傻瓜教授特性:如果你不小心将非静态成员添加到这样的类中,将显示编译错误。如果你试图实例化一个静态类,将会显示另一个编译时错误。使用de-facto静态类当然,你可以做两件事。



-SA
No, you cannot derive a class from a static class (which only can be nested in Java). But why not?

Strictly speaking, this is a voluntary kind of decision. The short answer would be: this because the authors of Java technology designed it this way. However, one rational point behind Java static classes is that they cannot be instantiated. In such situation, the role of inheritance would be quite limited.

It would be quite possible to create some OOP technology with inheritance on static classes. But you would need to decide how to interpret inherited static members. Each such member is a member of the whole class, not the instance. Perhaps if you have a member A.M of the class A, you may want to have two "M" if you derive new class B from A: A.M and B.M, otherwise you can tread them the same object. Does it make a whole lot of sense? It may depend on the other features of your technology.

This is not a considerable limitation in practice. I can tell you how to derive from static classes. Simply create some class which has only static members, but don't add the keyword static to the class itself. You will get the class which is static not formally, but only de-facto. You use such class as a base class, derive another class from it. Such "de-facto static class" will have no functional or performance/memory difference from a real static class. But as both classes have only static members, it won't give you much. You would only have a kind of "alias" naming for the same member. (In contrast to the idea described in previous paragraph, your A.M and B.M would be the same object.

Why having the ability to have real static class to be used as a base class? It would additionally add a fool-prof feature: if you accidentally add a non-static member to such class, the compilation error would be shown. Another compile-time error would be shown if you try to instantiate a static class. With the "de-facto" static class, you can do both things, of course.

—SA


这篇关于我们可以将超类声明为静态类吗?如果不是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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