can i make an arraylist with 2 object from different class?

how can i make an arraylist in the main with 3 itineraries: one without stop (route) and name d1 ,one with stop (indirectstop) and name d2, one without stop (route) and name d3. So ,i ask if there is any way to make an arraylist with two objects from one class and one from other class

Code:

public class Route {
private int id;   
private int aeroplane; 
private String departure; 
private String arrival; 
private ArrayList<Ticket> Tickets  ;  

public Route(){ 
    id = 0 ;
    aeroplane = 0  ;
    departure = " "; 
    arrival = " ";  
    Tickets = new ArrayList<>();
    
}

public Route(int ID, int aerop, String depar,String arriv,ArrayList<Ticket> tick ){
    id=ID;
    aeroplane=aerop;
    departure=depar;
    arrival=arriv;
    Tickets=tick;}

 public void addTicket(Ticket tick)
{
 Tickets.add(tick);
}

@Override
public void finalize(){
    Scanner input=new Scanner(System.in);
    System.out.println("The id of the train is:");
    id=input.nextInt();
    System.out.println("The aeroplane code is:");
    aeroplane=input.nextInt();
    System.out.println("The departure is:");
    departure=input.nextLine();
    System.out.println("The arrival is:");
    arrival=input.nextLine();

@Override
public String toString() {
    return "\nID: " + this.getId() + "\nAeroplane: " +this.getAeroplane() 
            + "\nDeparture: " + this.getDeparture() + "\nArrival" +this.getArrival() + "Tickets:" +this.getTickets();
}

And IndirectRoute, a subclass of Route.

public class IndirectRoute extends Route { 
    private String middlestop; 
    
    public IndirectRoute() 
    { 
      super();
      middlestop = "";
    }
    public IndirectRoute(String middle, int ID, int aerop, String depar,String arriv, ArrayList<Ticket> tick)
    {
      super(ID,aerop,depar,arriv,tick);
      middlestop = middle;
    }

    public String getMiddlestop() {
        return middlestop;
    }

    @Override
    public String toString() { 
        return super.toString() + "middlestop=" + middlestop + '}';
    }
}

Upvotes: 0

Views: 69

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338346

Yes, a list may contain objects of a certain type as well as objects of a subclass of that type. Java Generics handles this.

Here is a compact example, all in one .java file.

package work.basil.routing;

import java.util.List;
import java.util.UUID;

public class App
{
    public static void main ( String[] args )
    {
        App app = new App();
        app.demo();
    }

    private void demo ( )
    {
        List < Route > routes =
                List.of(
                        new Route() ,
                        new IndirectRoute() ,
                        new Route()
                );
    }
}

class Route
{
    public final UUID id = UUID.randomUUID();
}

class IndirectRoute extends Route
{
}

When we loop that list, Java can differentiate between elements of the superclass and elements of the subclass.

Current Java

Currently we would use instanceOf to differentiate between elements of the superclass and elements of the subclass

Notice one crucial issue with the following code. We, as the programmer, are responsible for getting the order right. We must consciously test for subclasses before we test for superclasses. The IDE/compiler provide no feedback if we get this order wrong.

for ( Route route : routes )
{
    String output = "OOPS! Unexpected type of `route`.";
    if ( route instanceof IndirectRoute )
    {
        output = "Instance of `IndirectRoute`, a subclass of `Route`. " + "Has ID: " + route.id;
    }
    else if ( route instanceof Route )
    {
        output = "Instance of `Route`. " + "Has ID: " + route.id;
    }
    System.out.println( "output = " + output );
}

When run.

output = Instance of `Route`. Has ID: 5a765835-40e4-4cc8-90e7-0687dd7f5362
output = Instance of `IndirectRoute`, a subclass of `Route`. Has ID: b57c9db3-8066-46d6-8f98-0d2d3fa4f835
output = Instance of `Route`. Has ID: a297586b-824e-4520-b760-1aebfd4e3446

Future Java

In the future, we will likely be able to use switch expressions combined with pattern matching for switch to differentiate between elements of the superclass and elements of the subclass. This new approach will be more concise and will provide more clarity of the programmer’s intention.

Notice that unlike the instanceof code seen above, we do get assistance from the IDE/compiler regarding the ordering out our cases. In the code below, if we had Route listed before IndirectRoute, our tooling would indicate the problem and suggest a reordering with the subclass before the superclass.

Caveat: The pattern matching feature is not yet released. Currently previewed in Java 19 (and 18, and 17).

for ( Route route : routes )
{
    String output =
            switch ( route )
                    {
                        case IndirectRoute x -> "Instance of `IndirectRoute`, a subclass of `Route`. " + "Has ID: " + route.id;
                        case Route y -> "Instance of `Route`. " + "Has ID: " + route.id;
                    };
    System.out.println( output );
}

When run.

Instance of `Route`. Has ID: 07152a33-5b98-4977-a62c-014e9fc3603d
Instance of `IndirectRoute`, a subclass of `Route`. Has ID: 448970bf-2c98-4310-8fff-2dbdac2d68c6
Instance of `Route`. Has ID: e9e7e0cb-0b28-420c-8dba-c2cb72007f2b

Upvotes: 1

Related Questions