对象转型(casting):
1、一个基类的引用类型变量可以是指向子类的对象。
2、一个基类引用不能访问子类对象新增加的成员(属性和方法)。
3、可以使用引用变量instaceof来判断该引用类型变量所“指向”的对象是否属于该类,或者该类的子类。
4、 子类对象可以作为基类对象使用,称为(upcasting)“向上转型”,基类对象当做来使用称为(downcasting)“强制转换”。
例如,代码如下:
Class Animal
{
Public String name;
//构造函数。
Animal(String name)
{
This.name = name;
}
}
Class Cat extends Animal
{
Public String eyesColor;
Cat(String n, String c)
{
Super(n);
eyeColor = c;
}
}
Class Dog extends Animal
{
Public String furColor;
Dog(String n, String c)
{
Super(n);
furColor(c);
}
}
Pulic class Test
{
Public static void main(String args[])
{
Animal a = new Animal("name");
Cat c = new Cat("Catname","blue");
Dog d = new Dog("dogname","black");
System.out.println(a instanceof Animal);
System.out.println(c instanceof Animal);
System.out.println(d instanceof Animal);
System.out.println(a instanceof Cat);
A = new Dog("bigyellow","yellow");
System.out.println(a.name);
System.out.println(a.furname);
System.out.println(a instanceof Animal);
System.out.println(a instanceof Dog);
Dog d1 = (Dog)a;//强制转换符。
System.out.println(d1.furColor);
}
}
内存分析:

父类引用指向子类的对象,只能看到父类的那部分,看不到子类的那部分。a只能看到名字。

强制转换后(向下转型)可以看到全部的内容。
很基础的东西,但很重要。
本文介绍了面向对象编程中对象转型的概念,包括向上转型和向下转型,并通过实例代码演示了如何使用引用变量进行类型判断及强制类型转换的过程。此外,还详细解析了父类引用指向子类对象时的内存可见性问题。

被折叠的 条评论
为什么被折叠?



