强制类型转换
方法有两种
1. 向上类型转换(upcast):比如说将CAT类型转换Animal类型 即将子类型转换为父类型
不需要在前面加小括号
2. 向下类型转换(downcast):比如将Animal类型转换为Cat类型 即将父类转换为子类(必须要使用强制类型转换)
程序:
public class PolyTest2
{
public static void main(String[] args)
{
/*Animal animal = new Cat();
Animal animal2 = new Animal();
animal2 = animal;
animal2.sing();
*/
/* Animal animal = new Cat();
Animal animal2 = new Animal();
animal = animal2;
animal.sing();
*/
//向上类型转换
Cat cat = new Cat();
Animal animal = cat; //当然使用这种方法写也是可以的 Animal animal = (Animal)cat;
animal.sing();
//向下类型转换
Animal a = new Cat();
Cat c = (Cat)a;
c.sing();
}
}
class Animal
{
public void sing()
{
System.out.println("animal is sing");
}
}
class Dog extends Animal
{
public void sing()
{
System.out.println("dog is sing");
}
}
class Cat extends Animal
{
public void sing()
{
System.out.println("cat is sing ");
}
}