I created a Car object using Vehicle class ( i.e Vehicle c = new Car() ), but my problem is how I will insert it into the list then Prompt the user to enter details for this object after the insertion in the list
import java.util.ArrayList;
import java.util.Scanner;
public class TestCar {
public static void main(String[] args) {
ArrayList<Car>list=new ArrayList<Car>();
Scanner in=new Scanner(System.in);
list.add(new Car());
list.add(new Car("Mitsubishi",1993,5,"Pajero"));
System.out.println("Enter Brand");
String Brand=in.nextLine();
System.out.println("Enter Year");
int Year=in.nextInt();
System.out.println("Enter Engine size");
double Enginesize=in.nextDouble();
System.out.println("Enter Model");
String Model=in.nextLine();
list.get(0).setBrand(Brand);
list.get(0).setYear(Year);
list.get(0).setEngineSize(Enginesize);
list.get(0).setModel(Model);
Veichle c = new Car(Brand, Year, Enginesize,Model); // Creating a new object
list.add(c); // This add will be wrong because cuz
//it will tell me to change type c to car
// so whats the correct add?
in.close();
}
}
You've created an ArrayList<Car>
- you can only add elements to that list that the compiler knows to be cars. So you could use:
list.add((Car) c);
or more simply, just declare the type of c
to be Car
to start with:
Car c = new Car(...);
Getting values out of the list, you're fine to use Vehicle
, because every Car
is a Vehicle
:
Vehicle vehicle = list.get(0);
Alternatively, you could change your list
variable to:
List<Vehicle> list = new ArrayList<Vehicle>();
Or equivalently:
List<Vehicle> list = new ArrayList<>();
(Note that it's generally preferrably to use the interface (List
in this case) for the variable type, even though you need to specify a concrete class (ArrayList
here) to create an instance.)
At this point, however, your code that modifies the brand etc wouldn't work if setBrand
is only defined on Car
, not vehicle - because list.get(0)
would only return a Vehicle
. You could potentially use:
Car firstVehicle = (Car) list.get(0);
... but obviously that would fail (at execution-time) if your list actually contained a non-Car vehicle.
Fundamentally, you need to decide whether your list should be able to contain any vehicle, or only cars.
As an aside, I'd strongly recommend that you start following Java naming conventions - use camelCase
for your local variables (year
, brand
etc.)
See more on this question at Stackoverflow