您的位置:首页 > 编程语言 > Java开发

java的向上转型与向下转型

2017-12-19 16:42 281 查看

1、java的向上转型

概念:定义一个父类的引用变量来指向一个子类的对象。

该引用变量可以调用父类中定义的属性和方法,对于非静态方法,如果子类中重写了该方法,则会引用java的动态绑定机制,实际调用子类的方法。

实例代码:

public class Father {

    public static int a = 15;

public int b = 110;

public static void aa()
{
System.out.println("this is father method aa...");
}

public void bb()
{
System.out.println("this is father method bb...");
}

}

public class Child extends Father{

public static int a = 5;

public int b = 10;

public static void aa()
{
System.out.println("this is child method aa...");
}

public void bb()
{
System.out.println("this is child method bb...");
}

public void cc()
{
System.out.println("this is child method cc...");
}

}

public class TestMain {
public static void main(String[] args) {
Father father = new Child();
System.out.println(father.a);
System.out.println(father.b);
father.aa();
father.bb();
//father.cc();
}

}

运行结果:

15

110

this is father method aa...

this is child method bb...

注意:1、引用变量只能调用父类中存在的变量和方法

           2、父类的变量无法被重写,所以引用变量实际调用的变量还是父类的变量,但是方法可以被重写,如果父类的方法被子类重写了,则引用变量调用的就是子类的方法 (java的动态绑定机制)

            3、静态方法是与类,而并非与对象相关联的,所以如果引用变量调用的方法是父类的静态方法,则最后实际调用的还是父类的静态方法,不会被覆盖。

2、java的向下转型

概念:子类实例对象赋值给父类引用,然后将父类引用向下转换成子类引用

代码实例:

public class TestMain {
public static void main(String[] args) {
Father father = new Child();
((Child) father).aa();

Father father2 = new Father();
((Child) father2).aa();
}

}

运行结果:

this is child method aa...

Exception in thread "main" java.lang.ClassCastException: study.Father cannot be cast to study.Child
at study.TestMain.main(TestMain.java:9)

如上所示,父类引用可以指向子类对象,但是子类引用不能指向父类对象,运行会报错。把父类引用指向子类对象然后再转换为子类引用的过程就是向下转型

向下转型的意思:很多人认为,java的向下转型意思不大,如果要用子类对象,我们直接创建一个子类的对象的引用不就行了吗,为什么还要多要向下转型这一过程,其实向下转型在泛型编程中经常用到,作用很大,具体可以查看这位朋友的博客:http://blog.csdn.net/xyh269/article/details/52231944

另,本博客也借鉴了一些另一个朋友的博客内容:http://blog.csdn.net/megustas_jjc/article/details/52600934

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: