1、多态(Polymorphism):我们说子类就是父类(玫瑰是花),多态的意思是:父类型的引用可以指向子类的对象。
public class PolyTest
{
public static void main(String[]args)
{
Flower rose = new Rose(); //多态,因为子类就是父类
rose.sing();
}
}
class Flower
{
public void sing()
{
System.out.println("sing");
}
}
class Rose extends Flower
{
}
2、多态:父类型的引用可以指向子类型的引用
例:
public class PolyTest
{
public static void main(String[] args)
{
Parent parent = new Parent();
parent.sing();
}
}
class Parent
{
public void sing()
{
System.out.println("parent is sing");
}
}
class Child extends Parent
{
public void sing()
{
System.out.println("child is sing"); //子类重写父类的方法
}
}
运行结果:
parent is sing
public static void main(String[] args)
{
//Parent parent = new Parent();
//parent.sing();
Parent p =new Child(); //父类型的引用指向子类型的引用,p是Parent 类型的,说明sing方法必须在父类中出现
p.sing(); //指向谁就会调用谁的方法
}
运行结果为:
child is sing
3、Parent p = new Child();当使用多态方式调用方法时,首先检查父类中是否有sing()方法,如果没有有则编译错误;如果有,再去调用子类的sing()方法。
public class polyTest2
{
public static void main(String[] args)
{
Animal a = new Dog();
Dog dog = (Dog) a; //向下类型转换
dog.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");
}
}
4、一共有两种类型的强制类型转换:
a)向上类型转换(upcast):比如说将Cat类型转换为Animal类型,即将子类转换为父类型,对于向上类型转换,不需要显式指定。
Cat cat = new Cat();
Animal animal = cat; //向上类型转换不需要强制类型转换,Animal animal = (Cat) cat;
animal.sing();
b)向下类型转换(downcast),比如将Animal类型转换为Cat类型。即将父类型转换为子类型。对于向下类型转换,必须要显式指定(必须要使用强制类型转换)。
Animal a = new Cat();
Cat cat = (Cat) a;
cat.sing();
代码举例:
public class PolyTest3
{
public static void main()
{
Fruit f = new Pear();
f.run();
}
}
class Fruit
{
public void run()
{
System.out.println("fruit is running");
}
}
class Pear extends Fruit
{
public void run()
{
System.out.println("pear is running");
}
}
运行结果
pear is running
public static void main(String[] args)
{
pear p = (Pear)f;
p.run();
}
运行结果:
pear is running
代码示例:
{
/*
public void run(BMW bmw)
{
bmw.run();
}
public void run(QQ qq)
{
qq.run();
}
*/
public void run(Car car)
{
car.run();
}
public static void main(String[] args)
{
/*
PolyTest5 test = new PolyTest5();
BMW bmw = new BMW();
test.run(bmw);
QQ qq = new QQ();
test.run(qq);
bmw.run();
QQ qq = new QQ();
qq.run();
*/
PolyTest5 test = new PolyTest5();
/*
BMW bmw = new BMW();
Car car = bmw;
*/
Car car = new BMW();
test.run(car);
QQ qq = new QQ();
/*
Car car = qq;
car.run();
*/
test.run(qq); // 向上类型转换
}
}
class Car
{
public void run()
{
System.out.println("car is running");
}
}
class BMW extends Car
{
public void run()
{
System.out.println("BMW is running");
}
}
class QQ extends Car
{
public void run()
{
System.out.println("QQ is running");
}
}
QQ is running