twz1015

instanceof和类型转换

  1. 类型转换
    •  父类引用转向子类对象
    • 把子类转换为父类,向上转型
    • 把父类转换为子类,向下转型,强制转换
    • 方便方法的调用
    public static void main(String[] args) {
//instanceof
// Object->Person->Student
// 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);

//Person->Student
// Student student=new Student();
// System.out.println(student instanceof Student);
// System.out.println(student instanceof Person);
// System.out.println(student instanceof Object);
// System.out.println(student instanceof Teacher);

Person person1=new Student(); //父亲--->>子类
//person将这个对象转化为Student类型,我们就可以使用Student类型的方法了
Student student= (Student) person1;
student.eat();

((Student) person1).eat();
//子类转父类可能丢失原来子类的方法
// Student student1=new Student();
// Person person=student1;
//person.eat;//无法再调用自己的eat

posted on 2023-03-20 20:28  小谭吖  阅读(14)  评论(0编辑  收藏  举报

导航