Java 向上转型和向下转型
Java 向上转型和向下转型
Java 向上转型后不能使用子类中的新方法,对于使用被重写的方法名时还是用重写后的方法体(即子类中的方法体)。
Java 向下转型运行时会报错(注意并不是int与char之间的转换)。但是问题的关键是编译时不会报错! 详见具体运行实例:
[java]- package com.han;
- public class Test {
- int[] a;
- int b=10;
- public Test(){
- int[] a={8,9};
- try{
- System.out.println(a[0]);
- }catch(ArrayIndexOutOfBoundsException e){
- String strFile=e.getMessage();
- System.out.println(strFile);
- new InnerClass();
- }
- }
- void testException() {
- }
- void testOwned(){
- System.out.println("It is Test's own method.");
- }
- void test1() {
- a=new int[]{1,2,3};
- a[2]=b;
- System.out.println(a[2]);
- }
- public static void main(String[] args) {
- Test t=new Test();
- t.test1();
- for(int e:t.a){
- System.out.println(e);
- }
- }
- class InnerClass{
- InnerClass(){
- System.out.println("OK");
- }
- }
- }
- package com.han;
- /**
- * @author Gaowen HAN
- *
- */
- public class Test2 extends Test{
- @Override
- void test1(){
- System.out.println("This is a overriding.");
- }
- void newMethodTest2(){
- System.out.println("This is a new method for Test2.");
- }
- public static void main(String[] args) {
- Test2 t1=new Test2();
- t1.testOwned();
- t1.newMethodTest2();
- t1.b=11;
- t1.test1();
- for(int e:t1.a){
- System.out.println(e);
- }
- }
- }
- package com.han;
- public class Test3 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- @SuppressWarnings("unused")
- Test2 t2=(Test2) new Test();//运行时报错Exception in thread "main" java.lang.ClassCastException: com.han.Test cannot be cast to com.han.Test2
- //System.out.println(t2.b);
- }
- }
而对于向上转型后则是可以用instanceof关键字来判断对象引用的到底是哪个子类。
评论暂时关闭