Java上下转型


class Chinese {
    public static void print() {
        System.out.println("this   is   中国人");
    }
}
class Guangdongren extends Chinese {
    public static void print() {
        System.out.println("this   is   广东人   ");
    }
}
class HunanRen extends Chinese {
    public static void print() {
        System.out.println("this   is   湖南人   ");
    }
}
class GuangzhouRen extends Guangdongren {
    public static void print() {
        System.out.println("this   is   广州人     ");
    }
}
public class TestUpAndDownChange {
    public static void main(String args[]) {
        Chinese c = new Chinese();// 这样编译可以通过,但运行会抛出异常
        HunanRen h = (HunanRen) c;// 这是因为向下转型错误,中国人不一定是湖南人,这里
        // 是不是可以这样理解要将c强制转换成一个HunanRen
        HunanRen h1 = new HunanRen();// 这样就没有问题,这是向上转型,
        Chinese c1 = (Chinese) h; // 湖南人一定是中国人这是是否可以理解为将h转换成Cinese
        Chinese h2 = new HunanRen();// 向上转型
        h.print();
    }
}

package test;
 class Animal {
    static {
      System.out.println("Animal static code block ");
    }
    {
        System.out.println("Animal  code block ");
      }
  Animal(){
     System.out.println("Animal constructor");
  }
}
class Tiger extends Animal {
       static {
              System.out.println("Tiger static code block ");
            }
            {
                System.out.println("Tiger  code block ");
              }
    Tiger(){
    System.out.println("Tig constructor ");
  }
}
class Dog extends Animal {
}
public class Zoo {
        public static void main(String [] args)throws Exception {
            //concurrent 并发 precision 精密
            //System.out.println("new Zoo before");
            //Zoo z = new Zoo();
            //Class c = Class.forName("test.Dog",false,z.getClass().getClassLoader());
            //Class c = Class.forName("test.Dog");
            //Class c = Class.forName("test.Dog");
            //System.out.println("initilize before ");
            //Animal dog = (Animal)c.newInstance();
            Animal dog1 =      (Animal) new Tiger();
           
            if(dog1 instanceof  Animal){
                System.out.println(new StringBuffer(" aaa  "));
                   
            }
           
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值