美文网首页
instanceof和类型转换

instanceof和类型转换

作者: 哈迪斯Java | 来源:发表于2021-09-23 20:36 被阅读0次

instanceof:判断一个对象是什么类型

package oop.Demon6;

public class Person {
public void run(){
System.out.println("run");
}

}

package oop.Demon6;

public class Student extends Person {
public void go(){
System.out.println("go");

}

}
/*
多态注意事项:
1.多态是方法的多态,属性是没有多态的
2.父类和子类,有联系,类型转换异常!一般表示出:classcastexpection!
3.存在条件:继承关系,方法需要重写,父亲的引用指向子类对象=== Father f1 = new Son();

哪些方法不适合重写:
1.static 方法,属于类,但是它不属于实例
2.final 常量;
3.priva方法;

*/

/*
//Object>String
//Object>Person>Teacher
//Object>Person>Student
Object object = new Student();

    //System.out.println(x instanceof y);//能不能编译通过

    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(person instanceof String);

    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);
    //System.out.println(student instanceof Teacher);
    //System.out.println(student instanceof String);

}

*/

package oop;

import oop.Demon6.Person;
import oop.Demon6.Student;
import oop.Demon6.Teacher;

public class Application {
public static void main(String[] args) {
//类型之间的转化:父 子

    //子类转为父类,可能丢失自己本来的一些方法
    //高            低
    Person obj = new Student();

    //student将这个对象转换为Student类型,我们就可以使用student类型的方法了

    Student student = (Student) obj;
    student.go();
}

}

/*
1.父类引用指向子类的对象
2.子类转换为父类,需要向上转型:不用强制转型
3.父类转换为子类:向下转型,强制转换
4.方便方法的调用,减少重复的代码!

抽象:封装、继承、多态。
抽象类,接口
*/

相关文章

网友评论

      本文标题:instanceof和类型转换

      本文链接:https://www.haomeiwen.com/subject/mlyogltx.html