关于向上和向下转型

package test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class Aa {
	void aMethod() {
		System.out.println("A method");
	}
}

class Bb extends Aa {
	void aMethod() {
		System.out.println("A method in B");
	}

	void bMethod1() {
		System.out.println("B method 1");
	}

	void bMethod2() {
		System.out.println("B method 2");
	}

}

public class Cc {
	public static void main(String[] args) {
		// 向上转型,aa无法调用Bb的bMethod1(),bMethod2()
		Aa aa = new Bb();
		// 下面调用的是Bb重写了的方法aMethod()
		aa.aMethod();
		// 向下转型
		Bb bb = (Bb) aa;
		bb.aMethod();// 依旧调用重写的方法aMethod()
		bb.bMethod1();
		bb.bMethod2();
		// 也是向下转型,编译无错,运行报错,因为aa2指向的是Aa
//		Aa aa2 = new Aa();
//		Bb bb2 = (Bb) aa2;
//		bb2.aMethod();
//		bb2.bMethod1();
//		bb2.bMethod2();
		// 但是:下面这段不会
		List<Integer> listA = new ArrayList<Integer>() {
			{
				add(new Integer("1"));
				add(new Integer("2"));
			}
		};
		Iterator it = listA.iterator();
		while(it.hasNext()){
        	Integer s = (Integer) it.next();//这块不会报错
        	System.out.print("a.listA:"+s+" , ");
        }
	}
}

你可能感兴趣的:(关于向上和向下转型)