JAVA面向对象八

1 多态

指的是多种形态

 表现: 

=同一个对象被造型为不同类的类型时,有不同功能

=对象的多态 :  我  你  水......所有对象都是多态的

>同一类型的引用指向不同的对象是时 ,有不同的实现

= 行为的多态 :cut() move() getImage()----所有抽象方法都是多态

=向上造型/自动类型转换:----------代码复用

超类型的引用指向派生类的对象

能点出来什么,看引用的类型

能造型成为的数据类型有: 超类+所有实现的接口 

>强制类型转换 , 成功的条件只有如下两种:

=引用所指向的对象,就是该类型

=引用所指向的对象,实现了该接口或继承了该类

>强转是若不符合如上条件,则发生了classcastException类型转换异常

建议 : 在强转之前先通过instanceof来判断引用对象是否是该类型

何时需要强转?

=想问的属性/行为在超类中没有 , 必须强转 , 强转之前先进行instanceof判断

  1.  
    public class MultiTypeDemo {
        public static void main(String[] args) {
            Aoo o = new Boo();
            Boo o1 = (Boo)o;     //引用o所指向的对象,就是Boo类型
            Inter o2 = (Inter)o; //引用o所指向的对象,实现了Inter接口
            //Coo o3 = (Coo)o; //运行时ClassCastException类型转换异常
            if(o instanceof Coo){ //false
                Coo o4 = (Coo)o;
            }else{
                System.out.println("o不是Coo类型");
            }
            /*
            System.out.println(o instanceof Boo);   //true
            System.out.println(o instanceof Inter); //true
            System.out.println(o instanceof Coo);   //false
             */
        }
    }
     
    interface Inter{ }
    class Aoo{ }
    class Boo extends Aoo implements Inter{ }
    class Coo extends Aoo{ }

补充重点:

instanceof是Java语言中的一个二元运算符,它的作用是:判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)的实例,即它左边的对象是否是它右边的类的实例,该运算符返回boolean类型的数据。

public class Test_instanceof {
    public static void main(String[] args) {
        String s = "Hello";
        int[] a = {1, 2};
        if (s instanceof String) {
            System.out.println("true");
        }
        if (s instanceof Object) {
            System.out.println("true");
        }
        if (a instanceof int[]) {
            System.out.println("true");
        }
    }
}
原文链接:https://blog.csdn.net/weixin_40995778/article/details/83307533

2 接口可以继承多个接口

interface Inter1{
    void show();
}
interface Inter2{
    void test();
}
interface Inter3 extends Inter1,Inter2{
    void say();
} 

3 何时需要强转?

=想问的属性/行为在超类中没有 , 必须强转 , 强转之前先进行instanceof判断

ArrayIndexOutOfBoundsException:数组下标越界异常

NullPointerException:空指针异常

ClassCastException:类型转换异常

5 检测碰撞

 

public boolean isHit(SeaObject other){
    //假设this指代潜艇 other指代炸弹

    int x1=this.x-other.width;//x1:潜艇的x-炸弹的宽
    int x2=this.x+this.width;//x2:潜艇的x+潜艇的宽
    int y1=this.y-other.height;//y1:潜艇的y-炸弹的高
    int y2=this.y+other.height;//y2 潜艇的y+炸弹的高
    int  x=other.x;//炸弹的x
    int y=other.y;//炸弹的的y
    return x>=x1 && x<=x2 && y>=y1 && y<=y2;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值