为什么在Java中嵌套抽象类 [英] Why nested abstract class in java

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

问题描述

我想知道拥有嵌套抽象类意味着什么?例如,

I am wondering what does it mean to have a nested abstract class ? for example,

   abstract class A{

          abstract class B{

          }
   }

是否存在我们可能需要的使用案例或方案,例如设计?还是在这种模式下有用的东西?以及为什么Java允许我们这样做?

Are there any use cases or scenario that we might need such as design ? or is there something useful in such pattern ? and why Java allows us to do it ?

推荐答案

在设计中,您希望基类 class A 仅为其派生类显示一个接口。这意味着,您不希望任何人实际实例化基类的对象。您只想对其 upcast (隐式upcasting,这将为您提供多态行为),以便可以使用其接口。这可以通过使用abstract关键字使该类抽象化来实现。另一方面,您只想使用 Class A 的部分功能,因此可以创建 Class B (作为子代)来减少系统之间的耦合或实现依赖性,并防止重复

In design, you want the base class class A to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which gives you polymorphic behavior), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword. In other hand you want to use only part of functionality of class A so you create class B (as child) to reduce the coupling or implementation dependencies between systems and prevent duplicates.

但是在定义内部类时请记住,没有内部类的代码更易于维护和可读。当您访问外部类的私有数据成员时,JDK编译器将在外部类中创建包访问成员函数,以供内部类访问私有成员。这留下了安全漏洞。通常,我们应该避免使用内部类。仅当内部类仅在外部类的上下文中相关和/或内部类可以设为私有,以便只有外部类可以访问它时,才使用内部类。 内部类主要用于实现在外部类的上下文中使用的帮助器类,例如Iterators,Comparators等。关于抽象类,它对于助手应该是抽象的,假设您的 helpers 应该太复杂而无法为他们编写抽象形式。

But bear in mind when you define an inner class, code without inner classes is more maintainable and readable. When you access private data members of the outer class, the JDK compiler creates package-access member functions in the outer class for the inner class to access the private members. This leaves a security hole. In general we should avoid using inner classes. Use inner class only when an inner class is only relevant in the context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc which are used in the context of an outer class. About abstract class, it should be abstract to helpers, suppose your helpers should be too complicated to write abstract form for them.

在您的情况下,我不记得嵌套抽象类的广泛使用,也许在 Swing 的世界中。

In your case, I don't remember extensive usage of nested abstract classes, maybe in Swing world.

这篇关于为什么在Java中嵌套抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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