多态
课堂笔记
代码
package com.oop;
import com.oop.demo06.Person;
import com.oop.demo06.Student;
public class Application {
public static void main(String[] args) {
//一个对象的实际类型是确定的
//new Student();
//new Person();
//可以指向的引用类型就不确定了:父类的引用指向了子类
//能调用的方法都是自己的或继承父类的
Student s1 = new Student();
Person s2 = new Student();
Object s3 = new Student();
s2.run();//子类重写了父类的方法,执行子类的方法
s1.run();
//对象能执行哪些方法,主要看对象左边的类型,和右边关系不大
}
}
Student类
package com.oop.demo06;
public class Student extends Person{
public void run() {
System.out.println("陈ying");
}
}
Person类
package com.oop.demo06;
public class Person {
public void run() {
System.out.println("chenying");
}
}
instance of类型转换
课堂截图
代码
package com.oop;
import com.oop.demo04.Teacher;
import com.oop.demo06.Person;
import com.oop.demo06.Student;
public class Application {
public static void main(String[] args) {
Object object = new Student();
//System.out.println(X instanceof Y);// 能不能编译通过 ,取决于X和Y是否是父子关系或更远,但需为一条直线
System.out.println(object instanceof Student); //true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof String);//false
}
}