关于向上和向下转型


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+" , ");
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值