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

查看:26
本文介绍了为什么在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 仅呈现其派生类的接口.这意味着,您不希望任何人实际实例化基类的对象.您只想向上转换(隐式向上转换,它为您提供多态行为),以便可以使用它的接口.这是通过使用 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 编译器会在外部类中创建包访问成员函数,供内部类访问私有成员.这留下了安全漏洞.一般来说,我们应该避免使用内部类.仅当内部类仅在外部类的上下文中相关和/或内部类可以设为私有以便只有外部类可以访问它时才使用内部类.内部类主要用于实现在外部类的上下文中使用的辅助类,如迭代器、比较器等.关于abstract class,对helpers来说应该是抽象的,假设你的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天全站免登陆