Before java 7, the Arraylist should be declared as before; since java 5, the generic has been introducled;
//before Jave 7, ArrayList<String> list = new ArrayList<String>();
//In Java 7, ArraryList<machine> = new Arryaylist<>();
//Class file named App.java begins here;
class Machine
{
public String toString()
{
return system.out.println("Machine is starting");
}
}
public void Start()
{
return system.out.println("Machine is starting");
}
class Camero extends Machine
{
private int brand;
public void snap()
{
System .out.println("i am snapping");
}
public void Start()
{
return system.out.println("Machine is starting");
}
public int getBrand()
{
return brand;
}
@override
public String toString()
{
return "I am a camero"
}
}
class App{
public static void main()
{
ArrayList<String> list = new ArrayList<String>();
/*
Bear in mind that ArrayList<Camero> is not a subclass of ArrayList<Machine>
Which could be work around by using wildcards and Generics
*/
ArrayList<Machine> list2 = new ArrayList<Machine>();
ArrayList<Camero> list3 = new ArrayList<Camero>();
}
public static void showList(ArrayList<string> list)
// 1.public static void showList(ArrayList<?> list)
// 2.public static void showList(ArrayList<? extends Machine> list)
// 3.public static void showList(ArrayList<? super Camero> list)
{
for(String value: list)// 1. for(Object value: list)
// 2. for(Machine value:list))
System.out.println(value);
}}
Upcasting and Downcasting
//upcasting
Machine machine= new Machine();
Camero camero = new Camero();
Machine machine2=camero;
machine.start(); //this is ok
machine.tosnap();//this does not work as machine2 does not know snap existing.
//downcasting
Machine machine= new Camero();
Camero camero=(Camero)machine;
camero.start();
camero.snap();
Casting Numerical Values
float f1=8.6f;
float s=(float)8.6;