面向对象(四)

instanceof使用方法实例与分析

    public static void main(String[] args) {
        Father father = new Son(); 父类引用指向子类对象,本质还是父类
        System.out.println(father instanceof Son);//ture
        System.out.println(father instanceof Son2);//false
        System.out.println(father instanceof GrandFather);//ture
        System.out.println(father instanceof Object);//ture
        //System.out.println(father instanceof String);//编译报错
    }

        A X = new B();
        System.out.println(X instanceof Y);
        //若Y 在A-B的父子类从属关系链上,则为ture,否则为flase,详见第3、4行
        //若Y 与A-B的父子类从属关系链无关,则编译报错,详见7行

ps:GrandFather->Father->son=son2

instanceof前面的对象所属的类如果是后面类型的类或者是其子类的话,判断结果为ture,否则为false?


类型转换

public class Application {
    public static void main(String[] args) {
        //类型之间的转换:父(高) 子(低)
         //A指向父类(高)Father,无法使用子类(低)Son的go()方法
         Father A = new Son();
         //高转低需要强制转换,将A强制转换为Student类型就可以使用Student中的go()方法
        ((Student)A).go();

        //子类转换为父类可能会丢失自己的一些方法
        Son son = new Son();
        son.go();
        Father father = son;
    }
}

抽象类

public abstract class Action {
    //约束,有人帮我们实现
    //abstract:抽象方法,只有方法名,没有方法的实现
    public abstract void doSomething();
}
  • 有abstract修饰的类就是抽象类,用abstract修饰的方法就是抽象方法;

  • 抽象类不能实例化,只能靠子类实现,如果子类实现不了,就要靠子子类;

  • 抽象类里可以写普通方法,但是抽象方法必须在抽象类中;

  • 抽象类无实际作用,存在的意义是提高开发效率;

  • 继承抽象类的子类必须实现抽象类的所有方法,除非子类也是抽象类;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值