JavaSE学习03

JavaSE学习

多态

Person为父类,student为子类

一个对象的实际类型是确定的

  1. new Person();
  2. new student();

但是指向的引用类型就不确定了:

  1. student s1 = new student();
  2. Person s2 = new student(); //父类的引用指向了子类

子类能调用自己的方法,以及继承父类的方法;父类可以指向子类,但是不能调用子类独有的方法!!

如果需要调用,这时就可以使用强制类型转换**((student) s2).子类的方法**

注意事项
  1. 多态是方法的多态,属性没有多态
  2. 父类和子类有联系,若没有联系,会报类型转换异常 ClassCastException!
  3. 存在的条件:继承关系,方法需要重写,父类的引用指向子类对象 Father f1 = new son();
  4. 静态方法static 方法,属于类,它不属于实例
  5. final 常量
  6. 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;//自动类型提升,子类转换为父类

但是子类转换为父类时,会丢失自己本来的一些方法(提升为父类后,自己原来独有的方法无法使用)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值