JavaSE学习
多态
Person为父类,student为子类
一个对象的实际类型是确定的
- new Person();
- new student();
但是指向的引用类型就不确定了:
- student s1 = new student();
- Person s2 = new student(); //父类的引用指向了子类
子类能调用自己的方法,以及继承父类的方法;父类可以指向子类,但是不能调用子类独有的方法!!
如果需要调用,这时就可以使用强制类型转换**((student) s2).子类的方法**
注意事项
- 多态是方法的多态,属性没有多态
- 父类和子类有联系,若没有联系,会报类型转换异常 ClassCastException!
- 存在的条件:继承关系,方法需要重写,父类的引用指向子类对象 Father f1 = new son();
- 静态方法static 方法,属于类,它不属于实例
- final 常量
- private 私有方法不能重写。
instanceof关键字
instanceof是Java的一个关键字,左边是对象,右边是类,返回值是boolean类。它的具体作用是测试左边的对象是否是右边类或者其子类创建的实例对象,是,则返回true,否,则返回false。
teacher和student两个类都继承person类
Object>person>student
Object>person>teacher
Object>String
Object o = new student();//o是Objerct类,但他是student类的一个实例
System.out.println(o instanceof student);//true
System.out.println(o instanceof person);//true
System.out.println(o instanceof Object);//true
System.out.println(o instanceof teacher);//false
System.out.println(o instanceof String);//false
person p = new student();// p 是person类,但他是student类的一个实例
System.out.println(p instanceof student);//true
System.out.println(p instanceof person);//true
System.out.println(p instanceof Object);//true
System.out.println(p instanceof teacher);//false
System.out.println(p instanceof String);//编译报错
student s = new student();// s 是student类,他也是student类的一个实例
System.out.println(s instanceof student);//true
System.out.println(s instanceof person);//true
System.out.println(s instanceof Object);//true
System.out.println(s instanceof teacher);//编译报错
System.out.println(s instanceof String);//编译报错
类型转换
1.父类无法调用子类独有的方法,如果想调用,则必须将父类强转为子类
//Father为父类,son为子类,eat为子类独有的方法
Father f1 =new son();
f1.eat();//会报错
((son)f1).eat();//强转为子类,即可。
但是父类强转为子类,是大范围转换为小范围,可能会丢失一些方法
2.子类也可以转换为父类,不需强制转换,可以自动转换
son s1 = new son();
Father f1 = s1;//自动类型提升,子类转换为父类
但是子类转换为父类时,会丢失自己本来的一些方法(提升为父类后,自己原来独有的方法无法使用)