java中继承的概念

发布于 2024-09-27 21:12:24 字数 358 浏览 0 评论 0原文

嗨,我是 Java 新手....从 Objective C(iPhone 背景)移过来,

我们都知道 在这里我们不能使用多重继承......

替代方法是接口......

我的问题是......通过接口继承有任何意义......因为我们必须在我们的函数中定义函数的代码类......这里唯一有帮助的部分是变量...... 它就像 Objective C 中的单个 .h 类...

我只讨论该接口的函数...为什么要在那里声明...只是为了节省 2 或三行...就是这样...

请告诉为什么没有多重继承(原因很简单......)。

我知道这可能是一个不好的问题,但是……

我有点黑暗,请帮助……

hi i am new to java....moved from objective c (iphone background)

all we know that
here we cannot use multiple inheritance....

alternative way is interface......

my question is...... does inheritance through interfaces make any sense...because we have to define the code of function in our class.......only helping part here is variables...
it is like a single .h class in objective c...

i am talking about only functions of that interface...why to declare there....just to save 2 or three lines...that's it..

please tell why there is no multiple inheritance(simple reason...).

i know this may be a bad question to ask but.........

i am in little bit of dark please help.....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

看轻我的陪伴 2024-10-04 21:12:24

我喜欢斯蒂芬·施密特的回答。他对此解释得很清楚:
http://codemonkeyism.com/java-interview-questions-mutliple-inheritance/(链接失效)。

Java支持多重继承吗?

显然,Java 并不具有传统意义上的多重继承。所以正确的答案应该是“不”,或者“不,但是”或者“是,但是”。从那里人们可以探索几种方法。我首先会问 Java 语言设计者是否太愚蠢而无法实现多重继承?为什么 C++ 的人要实现它呢?那么我们大部分都会落在菱形反模式上:

在具有多重继承和知识组织的面向对象编程语言中,钻石问题是当两个类 B 和 C 继承自 A,而类 D 继承自 B 和 C 时出现的歧义。如果 D 中的方法调用A 中定义的方法(并且不重写该方法),并且 B 和 C 以不同的方式重写该方法,那么它从哪个类继承:B 或 C?

另外一个探索的方法是Java如何“模拟”多重继承?答案可能已经浮出水面,那就是接口。然后,我们通常会讨论 Java 中的接口,以及候选人过去是否、何时以及如何使用它们。界面有什么用处,他喜欢它们吗?我可以探索他的建模能力有多强,有时让他画一个带有界面的图表。我们继续讨论 Java 中的接口问题,以及当两个接口具有相同的静态字段并且一个类同时实现这两个接口时会发生什么 - Java 中的某种“多重继承”:

公共接口 I1 {
  字符串名称=“codemonkeyism”;
}

公共接口 I2 {
  字符串名称=“斯蒂芬”;
}

公共类 C 实现 I1, I2 {
  公共静态无效主(字符串[] args){
     System.out.println(NAME);
  }
}

说实话,语言设计者认为这在 Java 中不起作用:

C.java:3:对 NAME 的引用不明确,均为变量 NAME
             I1 中的变量 NAME 与 I2 中的变量 NAME 匹配
     System.out.println(NAME);
                        ^
1 个错误

还有很多方法可以和候选人一起探索,例如接口方法的修饰符是什么。 mixin 或 Trait 是否比接口更好地解决钻石问题?或者它们和多重继承一样糟糕吗?由于我不再非常喜欢继承,并且认为大多数用途都是一种代码味道,因此还可以与候选人讨论继承的缺点(例如紧密耦合)。
为什么?

我为什么要问这个问题?我从中学到了什么?继承是 OO 中非常基本的概念,每个 Java 开发人员都应该理解。对他的工作的反思以及超越对语法的了解也是一个基本特征,因此存在多重继承问题。我更喜欢能产生很多探索机会的问题。继承问题就是其中之一:多重继承、语言设计、代码味道、解决方案、接口、基于角色的开发。

I love this answer from Stephan Schmidt. He clearly explains about this:
http://codemonkeyism.com/java-interview-questions-mutliple-inheritance/ (link defunct).

Does Java support multiple inheritance?

Well, obviously Java does not have multiple inheritance in the classical sense of the word. So the right answer should be “no”, or “no, but” or “yes, but”. From there one can explore several ways. Mostly I start by asking if the Java language designers were too stupid to implement multiple inheritance? Why did the C++ guys implement it then? We mostly land at the Diamond Anti-Pattern then:

In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?

The other way to explore is how Java “emulates” multiple inheritance? The answer, which might already have surfaced, ist Interfaces. We then usually discuss interfaces in Java, if, when and how the candidate has used them in the past. What are interfaces good for, does he like them? I can explore how good he is at modelling and sometimes make him draw a diagram with interfaces. We go on with problems of interfaces in Java, and what happens when two interfaces have the same static fields and a class implements both – some kind of “multiple inheritance” in Java:

public interface I1 {
  String NAME = "codemonkeyism";
}

public interface I2 {
  String NAME = "stephan";
}

public class C implements I1, I2 {
  public static void main(String[] args) {
     System.out.println(NAME);
  }
}

Staying true, the language designer decided that this does not work in Java:

C.java:3: reference to NAME is ambiguous, both variable NAME
             in I1 and variable NAME in I2 match
     System.out.println(NAME);
                        ^
1 error

There are many more ways to explore with the candidate, e.g. what are the modifiers of interface methods. Are mixins or traits a better solution to the diamond problem than interfaces? Or are they just as bad as multiple inheritance? As I’m no longer very fond of inheritance and think most uses are a code smell, one can also discuss the down side of inheritance – tight coupling for example – with the candidate.
Why?

Why do I ask this question and what do I learn from it? Inheritance is a very basic concept in OO and should be understood by every Java developer. Reflection on his work and going beyond knowing the syntax is an essential trait also, therefor the multiple inheritance question. I prefer questions that spawn many opportunities to explore. The inheritance question is one of them: Mutliple inheritance, language design, code smells, solutions, interfaces, role based development.

少跟Wǒ拽 2024-10-04 21:12:24

我想在之前的回答中补充一些内容。

正如您从 Tilsan The Fighter 给出的深入解释中了解到的那样,Java 不支持多重继承。

或者,您应该使用委托设计模式之一。我知道有时代码看起来比使用多重继承完成的代码更冗长,但这是我们必须付出的代价。

您问了一个问题,为什么需要创建实现多个接口的类?我想问你一个问题,为什么你需要界面?我认为答案是,这允许您将接口(契约)与具体实现分离,使模块独立,简化重构并使程序更加灵活:只有当具体实现被接口隐藏时,您才能切换实现。

如果您的类可以在不同的上下文中用作 A 和 B(其中 A 和 B 是接口),则该类应该实现 2 个接口。

示例: 假设您有一个仅声明一个方法的业务接口 Foo

int foo(String str);

现在您创建了几个实现 Foo 的类 A 和 B:

public class A implements Foo {
    public int foo(String s) {
        return s.length();
    }
}

public class B implements Foo {
    public int foo(String s) {
        return s.hashCode();
    }
}

现在您想要创建 Foo 的集合:

Collection<Foo> collection = new ArrayList<Foo>();
collection.add(new A());
collection.add(new B());

使用该集合的代码不知道任何关于具体实现,但它不会打扰它调用 foo()。

现在您希望对此集合进行排序。其中一种方法是实现另一个接口 Comparable:

public class A implements Foo, Comparable<Foo> {
    public int foo(String s) {
        return s.length();
    }
    public int compareTo(Foo o) {
        return getClass().getName().compareTo(o.getClass().getName());
    }
}

完成后,您可以说:

Collections.sort(collection);

并且集合将根据compareTo() 中定义的规则进行排序。

现在您可能希望序列化 A 和 B 的实例。为此,您必须实现另一个 Serialized 接口。幸运的是 Serialized 是一个特殊的接口,没有声明任何方法。 JVM 知道如何序列化和反序列化作为 Serialized 实例的对象。

public class A implements Foo, Comparable<Foo>, Serializable {
    public int foo(String s) {
        return s.length();
    }
    public int compareTo(Foo o) {
        return getClass().getName().compareTo(o.getClass().getName());
    }
}

B级看起来是一样的。

现在我们可以说:

DataOutputStream os = new DataOutputStream(new FileOutputStream("/tmp/foo.dat"));
os.writeObject(new A());
os.writeObject(new B());
os.flush();
os.close();

并将我们的对象存储在文件 /tmp/foo.dat 中。我们可以稍后读取这些对象。

我试图说明为什么我们需要实现多个接口的类:每个接口都赋予该类其行为。 Comparable 允许对此类实例的集合进行排序。可序列化允许序列化等。

I would like to add something to the previous answer.

As you understood from the deep explanation given by Tilsan The Fighter multiple inheritance is not supported by Java.

Alternatively you should use one of delegation design patterns. I know that sometimes the code looks more verbose than code done using multiple inheritance but this is the price we have to pay.

You asked a question why do you need to create class that implements more than one interface? I'd ask you a question why do you need interface at all? I think that the answer is that this allows you to separate interface (contract) from concrete implementation, make modules independent, simplify re-factoring and make programs more flexible: you can switch implementations only if the concrete implementation is hidden by interface.

If your class can be used in different contexts as A and as B (where A and B are interfaces) the class should implement 2 interfaces.

Example: Let's assume that you have a business interface Foo that declares only one method

int foo(String str);

Now you create a couple of classes A and B that implement Foo:

public class A implements Foo {
    public int foo(String s) {
        return s.length();
    }
}

public class B implements Foo {
    public int foo(String s) {
        return s.hashCode();
    }
}

Now you would like to create collection of Foo:

Collection<Foo> collection = new ArrayList<Foo>();
collection.add(new A());
collection.add(new B());

Code that uses this collection does not know anything about the concrete implementation but it does not bother it to invoke foo().

Now you wish to sort this collection. One of the ways is to implement yet another interface Comparable:

public class A implements Foo, Comparable<Foo> {
    public int foo(String s) {
        return s.length();
    }
    public int compareTo(Foo o) {
        return getClass().getName().compareTo(o.getClass().getName());
    }
}

Once you are done you can say:

Collections.sort(collection);

And the collection will be sorted according to the rule defined in compareTo().

Now you probably wish to serialize the instances of A and B. To do this you have to implement yet another interface Serializable. Fortunately Serializable is a special interface that does not declare any method. JVM knows to serialize and desirialize objects that are instances of Serializable.

public class A implements Foo, Comparable<Foo>, Serializable {
    public int foo(String s) {
        return s.length();
    }
    public int compareTo(Foo o) {
        return getClass().getName().compareTo(o.getClass().getName());
    }
}

Class B looks the same.

Now we can say:

DataOutputStream os = new DataOutputStream(new FileOutputStream("/tmp/foo.dat"));
os.writeObject(new A());
os.writeObject(new B());
os.flush();
os.close();

and store our objects in file /tmp/foo.dat. We can read the objects later.

I tried to show why do we need classes that implement several interfaces: each interface gives the class its behavior. Comparable allows sorting collection of such instances. Serializable allows serialization etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文