editor editor - 2 months ago 10
Java Question

How can I call the peek() method from another class (java)?

I have my stack, with its corresponding methods, in class A.
Now in class B, I want to create a new stack, calling the methods from class A. What I want to do, specifically, is peek at the elements of the stack in class A and then add the ones I like to the new stack in class B. Can someone help me out? I'm quite new at this!
P.S. I do want to know specifically how to do this across classes; I can figure out how to do it in the same class, but I'm trying to broaden my understanding of calling methods across classes. Thank you!

EDIT:
Someone asked for the code I refer to:
newStack.push(oldStack.(StackOne).peek());

I don't have that right, but here are the elements:
StackOne is the name of my first class, in which I've created the first stack, and oldStack is in that class.
I want to peek at these elements from StackTwo (my second class). If I like an element, I would push it from oldStack to newStack (ultimately resulting in something similar to what I've posted above, but that doesn't work).

Answer

Here is a class that incapsulates a stack inside of it.

MyStack.java

import java.util.Stack;

public class MyStack<T> {
    private Stack<T> stack;

    public MyStack() {
        stack = new Stack<T>();
    }

    public T peek() {
        return stack.peek();
    }

    public void push(T item) {
        stack.push(item);
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        MyStack<String> myStackA = new MyStack<String>();
        MyStack<String> myStackB = new MyStack<String>();

        myStackA.push("Hello");
        myStackA.push("Hi");

        myStackB.push(myStackA.peek());

        System.out.println(myStackA.peek()); //prints Hi
        System.out.println(myStackB.peek()); //prints Hi
    }
}
Comments