Java inheritance and composition (implementation stack)

I want to implement a stack in Java (using list interface: interface list)

I want to implement it in two different ways: using composition and inheritance

For inheritance, so far I have:

import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ListIterator;

 public class StackInheritance implements List {
      //implement list methods
 }

For composition, I have:

import java.util.List;

 public abstract class StackComposition implements List {
     // implement some standard methods
 }

 public class StackViaList extends StackComposition {
     // implement methods that have not been implemented in the abstract
     // class
 }

I'm confused where to start I've never used an interface before, so should I use the list method to "mimic" the stack, such as array or ArrayList?

In addition, for composition, I don't understand what methods should be used in stackcomposition and what methods should be used in stackvialist I'm a little lost between not fully understanding interfaces and inheritance and composition I can't seem to "get it"

Any help will be appreciated, thank you!

Solution

For composition, stack classes should have a list instead of implementing or extending list - based classes Inheritance is an "is a" relationship, while composition is an "has a" relationship

For example:

public class StackWithComposition
{
    // StackWithComposition HAS A List (rather than IS A List)
    private List myList = new ArrayList();

    public void push(object item)
    {
        // add item to myList,etc.
    }

    public object pop()
    {
        // return item at top (or end) of myList
    }

    // etc.
}

Note that you may want to set it as a generic class instead of dealing with the original object, but this may be an idea

In this case, the combination based solution may be better than the inheritance based solution When you inherit from a class / interface, you should ask yourself, is stack a list? Most stacks should not provide users with access to all the original list methods, so it's best to hide the faces you are using list as the internal data structure Using composite lists can completely hide the fact that you use lists as internal structures

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>