In: Computer Science
1. Implement the stack abstract data type. Write it as a separate class called Stack. For simplicity the data type to be stored in the stack is String but you can also use generic type.
2. Test your class implementation by calling push() and pop(). If the stack is empty (size equals zero) pop() should return null and print that “stack is empty”. If stack is full (size equals max) push() returns false and prints that “stack is full”.
This needs to be done in Java
Solution :
/******************************************************************************
The below code do the following as required in your question
1. Abstract class created wit name "MyStack" and contain method
declaration for push and pop
2. The abstact class methods for push and pop are implemented in
the MyDerived class by extenind the MyStack abstact class
4. The Main() method insatanitates the "MyDerived " class add
values to the Stack
5. The Main() method calls push method by passing a value which
checks size
6. The Main() mehtod clears the stack and call pop method which
check the stack is empty or not
*******************************************************************************/
import java.util.Stack;
abstract class MyStack
{
Stack<String> myStackVarible = new
Stack<String>();
abstract void MyPop();
abstract void MyPush(String value);
}
class MyDervied extends MyStack
{
void MyPop()
{
if(myStackVarible.isEmpty())
{
System.out.println("Stack is empty ");
System.exit(1);
}
}
void MyPush(String value)
{
if(myStackVarible.size()>0)
{
System.out.println("Stack is full ");
}
else
{
myStackVarible.add(value);
}
}
}
public class Main
{
public static void main(String[] args) {
MyDervied d = new
MyDervied();
// create stack by adding
values
d.myStackVarible.add("John");
d.myStackVarible.add("James");
d.myStackVarible.add("Thomas");
d.MyPush("Donald");
d.myStackVarible.clear();
System.out.println("Stack is
cleared");
d.MyPop();
}
}
Please find the screen shot of the output