Generic types and Wildcard types

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值