A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Write a program to create a class that stores the train reservation details. In addition, define a method that will display the stored details.

Programming steps:

1. create a Passenger class that contains details like pid, name and address  of Passenger:


public class Passenger
{
    int pid;
    String name;
    String address;
}



2. create a Constructor of Passenger class that contains details like pid, name and address  of Passenger:

  //parametrized constructor
    Passenger(int id, String nm, String add)
    {
        this.pid=id;
        this.name=nm;
        this.address=add;
    }
  

3. create a objects of Passenger class that contains details like pid, name and address  of Passenger:



Passenger  p1 = new Passenger(101,"Aman","Delhi");
        Passenger  p2 = new Passenger(102,"Navneet","Delhi");
        Passenger  p3 = new Passenger(103,"Heera","Delhi");
        Passenger  p4 = new Passenger(104,"BABU","Delhi");


4. create a objects of ArrayList class that contains list of Passenger details like pid, name and address of Passenger:



ArrayList  bookinglist = new ArrayList();
        bookinglist.add(p1);
        bookinglist.add(p2);
        bookinglist.add(p3);
        bookinglist.add(p4);




5. To view Clear list, you need to override the toString() method of Object class.


    @Override
    public String toString()
    {
        return pid+" "+name+" "+address;
    }





Complete Program code:

import java.util.ArrayList;
public class Passenger
{
    int pid;
    String name;
    String address;
   
    @Override
    public String toString()
    {
        return pid+" "+name+" "+address;
    }
   
    //parametrized constructor
    Passenger(int id, String nm, String add)
    {
        this.pid=id;
        this.name=nm;
        this.address=add;
    }
    public static void main(String a[])
    {
       
        Passenger  p1 = new Passenger(101,"Aman","Delhi");
        Passenger  p2 = new Passenger(102,"Navneet","Delhi");
        Passenger  p3 = new Passenger(103,"Heera","Delhi");
        Passenger  p4 = new Passenger(104,"BABU","Delhi");
       
        ArrayList  bookinglist = new ArrayList();
        bookinglist.add(p1);
        bookinglist.add(p2);
        bookinglist.add(p3);
        bookinglist.add(p4);
        System.out.println("Stored list is "+bookinglist);
    }
}


LEARN TUTORIALS

.

.