简体   繁体   中英

How to make a linked-list of different Classes?

I am relatively new to Java and to object oriented programming. I am learning about inheritance and OOP. I have this 1 class, lets say Bike, which has general information. Then I have these other classes, lets say Sports and Road, that extends Bike but I want to make a link list of these classes. So I would have one linked-list that contains both sports and road. But I am not sure how to go about and implement this. I know how to make a linked-list based on one class but not multiple ones. Thanks.

Just make a LL of the base class and add the elements you need.

import java.util.*;

public class ans{
    public static void main(String[] args){
    LinkedList<Parent> list = new LinkedList<Parent>();

    list.add(new ChildA());
    list.add(new ChildB());
    list.add(new Parent());

    for(Parent p: list)
        System.out.println(p);
    }
}

class Parent{
    public String toString(){
    return "I am a Parent";
    }
}

class ChildA extends Parent{
    public String toString(){
    return "I am a ChildA";
    }
}

class ChildB extends Parent{
    public String toString(){
    return "I am a ChildB";
    }
}

With an output

I am a ChildA
I am a ChildB
I am a Parent

As Bike is the superclass, the List of Bike type can be used to store the object of its subclasses.Something like this

Road r1=new road();
Road r2=new road();
Sports s1=new Sports();
Sports s2=new Sports();
List<Bike> bikeType=new ArrayList<Bike>();
bikeType.add(r1);
bikeType.add(r2);
bikeType.add(s1);
bikeType.add(s2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM