多态
1. 同一个方法可以根据发送对象不同而采用多种不同的行为方式
2. 一个对象的实际类型是确定的,但可以指向对象的引用类型有很多(父类或者有关系的类)
3. 多态存在的条件:
- 有继承关系
- 子类重写父类的方法
- 父类引用指向子类对象(Father f1 = new son();)
4. 注意:
- 多态是方法的多态,属性没有多态性
- instance of 类型转换 引用类型
- 父类和子类有联系,转换异常(ClassCastEeception!)
示例1
测试类
public class Application {
public static void main(String[] args) {
Student s1 = new Student();
Person s2 = new Student();
Object s3 = new Student();
s1.run();
s1.eat();
s2.run();
}
}
输出结果:
student run
student eat
student run
学生类(子类)
public class Student extends Person {
@Override
public void run() {
System.out.println("student run");
}
public void eat(){
System.out.println("student eat");
}
}
person (父类)
public class Person{
public void run(){
System.out.println("person run");
}
}
instance of
测试类
public class Application {
public static void main(String[] args) {
Object object = new Student();
System.out.println(object instanceof Student);
System.out.println(object instanceof Person);
System.out.println(object instanceof Object);
System.out.println(object instanceof Teacher);
System.out.println(object instanceof String);
System.out.println("=========================");
Person person = new Student();
System.out.println(person instanceof Student);
System.out.println(person instanceof Person);
System.out.println(person instanceof Object);
System.out.println(person instanceof Teacher);
System.out.println("===============================");
Student student = new Student();
System.out.println(student instanceof Student);
System.out.println(student instanceof Person);
System.out.println(student instanceof Object);
}
}
学生类(子类)
public class Student extends Person{
}
老师类(子类)
public class Teacher extends Person {
}
person类(父类)
public class Person {
}
类型转换
测试类
public class Application {
public static void main(String[] args) {
Person obj = new Student();
Student student =(Student) obj;
student.go();
((Student)obj).go();
}
}
输出结果:
go
go
person类
public class Person {
public void go(){
System.out.println("go");
}
}
学生类(子类)
public class Student extends Person{
}