在Java中欺骗单一继承? [英] Cheat single inheritance in Java?

查看:95
本文介绍了在Java中欺骗单一继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说有一种方法可以欺骗单继承并在Java中实现多重继承。有谁知道如何实现这个(没有使用界面)?

I have heard there is a way to cheat single inheritance and implement multiple inheritance in Java. Does anyone know how to implement this(with out using interface)?

只是出于好奇; - )

Just out of curiosity ;-)

推荐答案

当然可以,但这很棘手,你应该考虑这是否是你想要的方式。

想法是使用基于范围的继承加上基于类型的。对于内部目的而言,内部类继承外部类的方法和字段,这就是类型说话。它有点像mixins,其中外部类混合到内部类中,但不安全,因为您可以更改外部类的状态以及使用其方法。

Gilad Bracha (主要的java语言设计者之一)写了一篇论文来讨论这个问题。
因此,假设您想要在一些不相关的类之间共享一些内部使用的方法(例如,对于字符串操作),您可以创建它们的子类作为具有所有所需方法的类的内部类,并且子类可以使用来自超类和外部类的方法。

Sure you can, but it's tricky and you should really consider if that's the way you want to go.
The idea is to use scope-based inheritance coupled with type-based one. Which is type-talk for saying that for internal purposes, inner classes "inherit" methods and fields of the outer class. It's a bit like mixins, where the outer class is mixed-in to the inner class, but not as safe, as you can change the state of the outer class as well as use its methods.
Gilad Bracha (one of the main java language designers) wrote a paper discussing that. So, suppose you want to share some methods for internal use between some unrelated classes (e.g, for string manipulation), you can create sub classes of them as inner classes of a class that has all the needed methods, and the sub classes could use methods both from their super classes and from the outer class.

无论如何,对于复杂的类来说这很棘手,你可以使用静态导入(从java 5开始)获得大部分功能。但是,面试和酒吧测验的好问题是: - )

Anyway, it's tricky for complex classes, and you could get most of the functionality using static imports (from java 5 on). Great question for job interviews and pub quizzes, though ;-)

这篇关于在Java中欺骗单一继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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