Write a Java program to create a Stack collection of objects of a class
The code demonstrates the creation of a custom Complex class and its usage in a stack in Java. Let's go through the code step by step:
- The code defines a class called Create_ObjectClass. The main method is the entry point of the program. An integer variable i is declared and initialized to 0.
- A stack object named stack_list is created using generics. It is specified that the stack will contain elements of type Complex, which is a custom class defined later in the code.
- Several instances of the Complex class are created using the new keyword and pushed onto the stack using the push method. Each instance of Complex represents a complex number with a real and imaginary part.
- The System.out.println statement is used to print the string "Stack Items : ".
- A for loop is used to iterate four times, popping elements from the stack. Each popped element is assigned to a variable C of type Complex.
- Inside the loop, the real and imaginary parts of the complex number are printed using the System.out.println statement.
- The Complex class is defined separately. It has two instance variables real and img, representing the real and imaginary parts of a complex number, respectively.
- The Complex class has a constructor that takes two parameters r and i to initialize the instance variables.
Source Code
import java.util.*;
public class Create_ObjectClass
{
public static void main(String[] args)
{
int i = 0;
Stack < Complex > stack_list = new Stack < Complex > ();
stack_list.push(new Complex(10, 50));
stack_list.push(new Complex(20, 60));
stack_list.push(new Complex(30, 70));
stack_list.push(new Complex(40, 80));
System.out.println("Stack Items : ");
for (i = 0; i < 4; i++)
{
Complex C = stack_list.pop();
System.out.println(C.real + " + " + C.img + "i");
}
}
}
class Complex
{
int real, img;
Complex(int r, int i)
{
real = r;
img = i;
}
}
Output
Stack Items :
40 + 80i
30 + 70i
20 + 60i
10 + 50i