java学习第十一次笔记
一、多态
1.概念
什么是多态?
同一个对象,在不同时刻表现出来的不同形态
多态的前提
1要有继承或实现关系
2要有方法的重写
3要有父类引用指向子类对象
2.特点
成员访问特点
成员变量
编译看父类,运行看父类
成员方法
编译看父类,运行看子类
3.多态作用
提高程序的扩展性。定义方法时候,使用父类型作为参数,在使用的时候,使用具体的子类型参与操作
弊端
不能使用子类的特有成员
4.两种转型
向上转型
父类引用指向子类对象就是向上转型
向下转型
格式:子类型对象名=(子类型)父类引用;
二、代码展示
public class Animal{
public void eat(){
System.out.println("动物吃东西");
}
}
publicclassCatextendsAnimal{
public Cat(){
}
public Cat(String name,int age){
super(name,age);
}
@Override
public void eat(){
System.out.println("猫吃鱼");
}
}
public class Dog extends Animal{
public Dog(){
}
public Dog(Stringname,int age){
super(name,age);
}
@Override
public voideat(){
System.out.println("狗吃骨头");
}
}
public class Demo03Main {
public static void main(String[] args) {
Animal animal=new Cat();
animal.eat();
Cat cat = (Cat) animal;
cat.catchMouse();
}
}
public class Demo03lnstancof {
public static void main(String[] args) {
Animal animal=new Dog();
animal.eat();
giveMeAPet(animal);
}
public static void giveMeAPet(Animal animal)
{
if(animal instanceof Dog)
{
Dog dog=(Dog)animal;
dog.watchHouse();
}
if(animal instanceof Cat)
{
Cat cat=(Cat)animal;
cat.catchMouse();
}
}
}