java inheritance versus composition (implementing a stack)

落爺英雄遲暮 提交于 2019-12-07 11:56:50

问题


I am trying to implement a Stack in java (using the list interface: Interface List).

I want to implement it 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 am confused as to where to go from here. I have never used an interface before, so am I supposed to use the List methods to "mimic" a stack, using an Array or an ArrayList for example?

Also, for composition, I don't understand what methods should go into StackComposition and what should go into StackViaList. Between not fully understanding interfaces as well as inheritance and composition, I'm a bit lost. I can't seem to just "get it" yet...

Any help would be appreciated, thanks!


回答1:


For composition, the stack class should HAVE a list, not implement or extend a List-based class. Inheritance is an "IS A" relationship, whereas composition is a "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 would probably want to make this a generic class, rather than dealing with raw objects, but this would be the idea.

In this case, the composition-based solution is probably preferable over the inheritance-based solution. When you inherit from a class/interface, you should ask yourself, is the Stack a List? Most Stacks should not provide the user with access to all the raw List methods, so it's better to hide the face that you're using a List as the internal data structure. Using a composed List allows you to completely hide the fact that you're using a List as the internal structure.




回答2:


I don't think this is a real question. This is a "can you do my homework for me" question.

More meaningful questions would be:

  • What is the difference between inheritance and composition?
  • What are the advantages/disadvantages of implementing a stack with each?
  • What is a stack?

Andy gave good answers to all three.

Unfortunately, it looks like the original poster's teacher doesn't understand the concepts very well himself, since the assignment is nonsensical. A class that implements a java.util.List is not a stack, or rather, it is not safe to use as a stack, because it requires that non-stack-safe operations be public. A stack a rather more limiting interface than a list.

No wonder the original poster is confused.




回答3:


You have the concepts upside down.

Inheritance, as the word says is when you "take" from an existing object the functionality. This is know as IS-A relationship. For instance a Truck IS-A Vehicle.

In your first sample that's not inheritance, because you are not taking anything from the list. In your sample you are "implementing" that list not "extending" it.

Composition is when you build an object using others ( you're combining objects ). This is know as HAS-A relationship. For instance a Truck HAS-A wheel ( but is not a wheel ). In your sample you are "extending" ( inheriting ) from other object

Finally interface in OOP is the "contract" an object is commited to fulfill. What functions or messages an object will respond.

In Java "interface" is also an artifact where the methods an object will respond are defined.

So, for a stack you would have to define the methods an Stack has ( the interface )

public interface Stack {
     public void push( Object o );
     public Object pop();
}

Then using inheritance you can create the stack implementation. To do this you'll have to extend ( or inherit ) functionality from other class. Let's say ArrayList

 /**
  * Sample stack implementation using inheritance
  */
public class ArrayListStack extends ArrayList implements Stack {
// you use the keyword extends because you're inheriting from ArrayList
// and the keyword implements because you claim to respond to push and pop methods.

     public void push( Object o ) {
          this.add( o ); // add inherited from ArrayList
     }
     public Object pop() {
         return this.remove( this.size() -1 ); // remove inherited from ArrayList
     }
}

Since you're "inheriting" from ArrayList, most the what you need is already there. But, does this represents a IS-A relatioship? Is it true that a Stack IS-An ArrayList always?

To implement the stack using composition you have to "combine" your object with another.

  /**
   * Sample stack implementation using composition
   */ 
 public class ComposedStack  implements Stack {
      // you didn't extend anything here

      // But you'll need another object to help you 
      // to do the work.
      private ArrayList holder = .... // Should be declared as List holder = ....


    public void push( Object o ) {
         this.holder.add( o );
    }

    public Object pop() {
        return this.holder.remove( this.holder.size() -1 );
    }
 }

The implementation is very similar, you're using "add" and "remove" methods from the ArrayList

The difference is the in the first case using inheritance you are not only using these two methods, but you are coupling your object completely to the ArrayList itself ( because you have also inherit all the other methods, and attribute the ArrayList has )

When you use composition, you don't couple your object to the arraylist ( or the coupling is low, which is a good thing ) You are simply using another object to help you to do the work. In this case it was an ArrayList.

From the outside ( using composition ) , you don't see there is an ArrayList inside, that's information hiding. The user ( the client ) of your class only see two methods available "push" and "pop" and there's nothing more that could be done with your class. It looks like a "real" Stack.

With inheritance ( using extends keyword ), the client of the class see's also all the methods from ArrayList although you may want that only pop and push are used, nothing prevents from the client to use "removeRange" for instance.

Conclusión: Understanding the differences between is-a and has-a relationships is essential for OO technology. I hope this help you.




回答4:


class stack
{

    int n,item,top;
    public stack()
    {
        n=7;
        top=-1;
    }}
    class student extends stack
    {
    int [] stk=new int[4];
    public void insert(int a)
    {
        if(top>=n-1)
        System.out.println("over flow");
        else
        {
            top++;
            stk[top]=a;
        }   
    }
        public void deletestk()
    {
        if(top<0)
            System.out.println("under flow");
            else
            {
                item=stk[top];
                top--;
                    System.out.println("deleted item are"+item);
            }
    }
        public void destroy()
    {
        if(top<0)
            System.out.println("under flow");
            else
            {

            top=-1;
    }
    }
    public void view()
    {
        int i;
        i=top;
        while(i>=0)
        {
                System.out.println(stk[i]);
                i--;
        }
    }   

    }
    class stackfloat extends stack
    {

        float [] stk=new float[6];
    }
    class stkstring extends stack
    {
        String [] stk=new String[5];
    }
    class stackmain
{
    public static void main(String arg[])
    {
        stack ob=new stack();
        student obj=new student();
            obj.deletestk();
        obj.insert(5);
            obj.insert(6);
                obj.insert(64);
                    obj.insert(45);
                        obj.insert(3);
                        obj.view();
                        obj.deletestk();
                        obj.view();
                        obj.destroy();
                        obj.view();



    }
}


来源:https://stackoverflow.com/questions/1419115/java-inheritance-versus-composition-implementing-a-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!