java inheritance versus composition (implementing a stack)

℡╲_俬逩灬. 提交于 2019-12-05 21:56:52

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.

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.

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.

Ahmad Hassan
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();



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