day12笔记--多态

1.方法的多态
就是方法的重写和重载。

package com.qfedu.a_test;

class Monkey{
	public void run() {
		System.out.println("猴子跑步");
	}
	public void run (String name) {
		System.out.println(name + "在跑步");
	}
}
class Cat extends Monkey {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
	}
	@Override
	public void run(String name) {
		// TODO Auto-generated method stub
		super.run(name);
	}
}
public class Demo2 {
	public static void main(String[] args) {
		
	}

}

2.对象的多态
概括:父类的引用指向子类的对象
例:Person person = new Son();
其中Son是Person的子类。

package com.qfedu.a_test;

class Person{
	public void eat() {
		System.out.println("吃米饭");
	}
}
class Son extends Person{
	@Override
	public void eat() {
		System.out.println("吃东西");
	}
	public void play() {
		System.out.println("玩游戏");
	}
}
public class Demo3 {
	public static void main(String[] args) {
		Person person = new Son();
		person.eat();
		//person.play();子类独有的父类无法调用
	}

}

***3.多态的转型***
3.1向上转型
父类的引用指向子类的对象
Animal animal = new Cat();

package com.qfedu.a_test;

class Animal1{
//这个是自动进行的
public void eat() {
System.out.println(“吃东西”);
}
}
class Dog extends Animal1{
@Override
public void eat() {
System.out.println(“吃骨头”);
}
}
class Cat1 extends Animal1{
@Override
public void eat() {
System.out.println(“吃老鼠”);
}
}
public class Demo4 {
public static void main(String[] args) {
Animal1 animal = new Dog();//父类引用狗这个子类对象
animal.eat();//吃骨头
Animal1 animal2 = new Cat1();//父类引用猫这个子类对象
animal2.eat();//吃老鼠
}

}

3.2向下转型
概括:先进行向上转型,在进行向下强转
          Person person = new Son();
		Son son = (Son)person;

package com.qfedu.b_test;

class Person{
public void eat() {
System.out.println(“吃食物”);
}
}
class Son extends Person{
@Override
public void eat() {
System.out.println(“吃雪糕”);
}
public void play() {
System.out.println(“玩火!危险!!!”);
}
}
public class Demo1 {
public static void main(String[] args) {
Person person = new Son();
Son son = (Son)person;//此时已经进行了强转
son.play();//可以调用自己的
son.eat();//
}

}

***4.instanceof关键字***
比较操作符,返回值是布尔类型的数据
目的是为了在强转的时候不出现问题
(用辈分的方式进行比较)
格式:
对象引用  instanceof  运行类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值