简体   繁体   English

如何在java中应用多态?

[英]How to apply polymorphism in java?

I have a question on how to have one method call work on two different classes of objects in Java?我有一个关于如何在 Java 中对两个不同类的对象进行一个方法调用的问题? For example, if both classes SListNode and DListNode want to use the same method size() to measure the length of a list.例如,如果 SListNode 和 DListNode 两个类都想使用相同的方法 size() 来测量列表的长度。 I would like to define the size method only once, instead of writing out explicitly twice in both SListNode and DListNode classes.我想只定义一次 size 方法,而不是在 SListNode 和 DListNode 类中明确写出两次。

I guess inheritance is necessary.我想继承是必要的。 For instance, define a superclass Size, which contains the size() method.例如,定义一个超类 Size,其中包含 size() 方法。 Both SListNode and DListNode are subclasses of Size. SListNode 和 DListNode 都是 Size 的子类。 However, a specific type of list is required in the definition of size() method in this way.但是,这种方式在 size() 方法的定义中需要特定类型的列表。 Hence, the method cannot be applied to both SListNode and DListNode.因此,该方法不能同时应用于 SListNode 和 DListNode。

I was wondering what should the inheritance structure look like or if there is any standard way to solve this kind of question?我想知道继承结构应该是什么样子,或者是否有任何标准方法可以解决此类问题? I guess there is and this is why java has polymorphism.我猜有,这就是为什么 java 具有多态性。 But it is hard for me to find out...但是我很难发现......

What you want to do is to put the method size() as a method of a parent class, such as a class called Node.你要做的就是把方法size()作为一个父类的方法,比如一个叫做Node的类。

Then make SListNode and DListNode extend Node.然后让 SListNode 和 DListNode 扩展 Node。 The method size() will be inherited, and so you only need to implement it in the class Node.方法 size() 会被继承,所以你只需要在类 Node 中实现它。

Here is the structure:这是结构:

The Parent Class:家长班:

public class Node {

  //Parent class

  //size() method will be inherited by children
  public void size(){
    //Put implementation of size() here
  }
}

The Children:这些孩子:

public class DListNode extends Node {

  //size() method is inherited

  // put the rest of your body here

}


public class SListNode extends Node {

  //size() method is inherited

  // put the rest of your body here


}

Hope This helps :)希望这可以帮助 :)

You should think different.你应该有不同的想法。 For exemple : create an abstract class ListNode and put non specific code inside it (don't implement the lists itself. Implement the size method for listNode. For exemple the size method could just read a property (protected int size)例如:创建一个抽象类 ListNode 并将非特定代码放入其中(不要实现列表本身。为 listNode 实现 size 方法。例如,size 方法可以只读取一个属性(受保护的 int 大小)

Create SListNode and DListNode class, extending ListNode, and implementing specific code.创建SListNode和DListNode类,扩展ListNode,实现具体代码。 Be sure to update the size property in your implementation.请务必在您的实现中更新 size 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM