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 运行类型