Pages

Sunday, 6 November 2016

Chapter 11 Exercise 10, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

11.10 (Implement MyStack using inheritance) In Listing 11.10, MyStack is implemented
using composition. Define a new stack class that extends ArrayList.
Draw the UML diagram for the classes and then implement MyStack. Write
a test program that prompts the user to enter five strings and displays them in
reverse order.

import java.util.ArrayList;

public class MyStack  extends ArrayList<Object> {


    public Object peek() {
        return get(size() - 1);
    }

    public Object pop() {
        Object o = get(size() - 1);
        remove(size() - 1);
        return o;
    }

    public void push(Object o) {
        add(o);
    }


    @Override /** Override the toString in the Object class */
    public String toString() {
        return "stack: " + super.toString();
    }
}

import java.util.Scanner;

public class Exercise_10 {

    public static void main(String[] args) {

        MyStack stack = new MyStack();
        Scanner input = new Scanner(System.in);
        System.out.print("Enter 5 strings... ");
        for (int i = 0; i < 5; i++) stack.push(input.next());

        System.out.println("Displaying them in reverse order.");
        while (stack.size() > 0) {
            System.out.println(stack.pop());
        }
    }
}

No comments :

Post a Comment