1. 向上转型 子类可自动向上转型
2. 向下转型 只能显式(强制)转型,否则会报错
3. 示例:
package p_java;
public class Bag {
protected void inUse(){
System.out.println("put into anything");
}
}
package p_java;
public class Wallet extends Bag {
protected void inUse(){
System.out.println("put into money");
}
}
/**
*
*/
package p_java;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
//向上转型
Bag bag = new Wallet();
bag.inUse();
//向下转型
Bag walletBag = new Wallet();
// Wallet wallet = walletBag; 报错
Wallet wallet =(Wallet)walletBag;
wallet.inUse();
}
}
4. 结果:
put in money
put in money