多态的形成有3个条件
- 有继承
- 有重写
- 有父类对象指向子类引用
多态形式
向上转型 父类 父类对象 = new 子类();
向下转型 要先发生向上转型,才能通过强转再转成子类类型
instanceof 关键字
判断第一个对象是否是某一个类的东西
if(animal instanceof Cat) {
Cat cat = new Cat();
cat.catchMouse();
}else if (animal instanceof Dog) {
Dog dog = new Dog();
dog.look();
} else {
code;
}
匿名对象
语法:new 类名()
;
功能:和正常有名字的对象的功能是相同的,依然具备了调用属性、方法的功能
使用场景:多数是用在传参、夹参,多数情况下配合构造器使用
好处:节约资源,栈的资源
程序运用
Person类(构造器)
public class Person {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Student类
public class Student extends Person{
public Student() {
}
public Student(String name, Integer age) {
super(name, age);
}
}
Teahcer类
public class Teacher extends Person{
public Teacher() {
super();
}
public Teacher(String name, Integer age) {
super(name, age);
}
}
School类(操作)
public class School {
public void start(Person person) {
if (person instanceof Teacher) {
System.out.println(person.getAge() + "岁的" + person.getName() + "老师开学去办公楼");
} else if (person instanceof Student) {
System.out.println(person.getAge() + "岁的" + person.getName() + "学生开学去寝室楼");
}
}
public void end(Person person) {
if (person instanceof Teacher) {
System.out.println(person.getAge() + "岁的" + person.getName() + "老师放学去逛街了");
} else if (person instanceof Student) {
System.out.println(person.getAge() + "岁的" + person.getName() + "学生放学坐车回家");
}
}
public static void main(String[] args) {
School school = new School();
Teacher teacher = new Teacher("王老师",43);
Student student = new Student("小明",21);
school.start(teacher);
school.start(student);
school.end(teacher);
school.end(student);
}
}