-7

I have a question on how to have one method call work on two different classes of objects in Java? For example, if both classes SListNode and DListNode want to use the same method size() to measure the length of a list. I would like to define the size method only once, instead of writing out explicitly twice in both SListNode and DListNode classes.

I guess inheritance is necessary. For instance, define a superclass Size, which contains the size() method. Both SListNode and DListNode are subclasses of Size. However, a specific type of list is required in the definition of size() method in this way. Hence, the method cannot be applied to both SListNode and 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. But it is hard for me to find out...

Tyler
  • 1
  • 1
    Take a look at: [Java Polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) – lkq Apr 04 '16 at 21:57
  • 3
    `Java.polymorphism(apply);` – RaminS Apr 04 '16 at 21:58
  • 1
    Possible duplicate of [Polymorphism vs Overriding vs Overloading](http://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading) – wiredniko Apr 04 '16 at 22:16

2 Answers2

2

What you want to do is to put the method size() as a method of a parent class, such as a class called Node.

Then make SListNode and DListNode extend Node. The method size() will be inherited, and so you only need to implement it in the class 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 :)

Nikita V
  • 56
  • 6
0

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)

Create SListNode and DListNode class, extending ListNode, and implementing specific code. Be sure to update the size property in your implementation.

crashxxl
  • 682
  • 4
  • 18