多态 instanceof 类型转换

多态

一个对象的实际类型是确定的,可以指向的引用类型就不确定了:父类的引用可以指向子类

Student s1 = new Student();
Person s2 = new Student();

对象能执行哪些方法,主要看对象左边的类型,和右边关系不大

子类重写了父类的方法,执行子类的方法

Student 能调用的方法都是自己的或者继承父类的

Person 父类型,可以指向子类,但不能调用子类独有的方法

注意事项

  1. 多态是方法的多态,属性没有多态
  2. 父类和子类,有联系 否则会有类型转换异常 ClassCastException
  3. 存在条件:继承关系,方法需要重写,父类引用指向子类对象
    例如
class Shape{}
class Square extends Shape{}
class Circular extends Shape{}

public class Demo01 {
    public static void draw(Shape s) {
        if (s instanceof Square){
            System.out.println("绘制正方形");
        }else if (s instanceof Circular){
            System.out.println("绘制圆形");
        }else{
            System.out.println("绘制父类图形");
        }
    }

    public static void main(String[] args) {
        draw(new Shape());
        draw(new Square());
        draw(new Circular());
    }
}
/*输出
绘制父类图形
绘制正方形
绘制圆形
 */

instanceof

判断一个对象是什么类型(前面的对象是否是后面类的实例)

System.out.println(X instanceof Y);//true or false
/*
Object>String
Object>Person>Teacher
Object>Person>Student
 */
Object object = new Student();

System.out.println(object instanceof Object);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false

类型转换

//子--->父   自动转换
Person student = new Student();
//父--->子   强制转换
//子类类型 子类对象=(子类类型)父类对象
Student person = (Student) new Person();
Student student = new Student();
Person person=student;//Person person=(Person)student;直接转也行
((Student) person).go();//强转

()内为要转成的类型

子类转换成父类,可能丢失自己本来的一些方法

posted @ 2021-07-20 19:04  valder-  阅读(52)  评论(0)    收藏  举报