java继承堆栈图,java继承与组合(实现堆栈)

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!

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值