Java基础 5.27

多态注意事项和细节讨论

  • 属性没有重写之说 属性的值看编译类型
package com.logic.poly_.detail_;

public class PolyDetail02 {
    public static void main(String[] args) {
        Base base = new Sub();
        System.out.println(base.count);
        Sub sub = new Sub();
        System.out.println(sub.count);
    }
}

class Base {
    int count = 10;
}

class Sub extends Base {
    int count = 20;
}
  • instanceOf比较操作符 用于判断对象的运行类型是否为XX类型或XX类型的子类型 
package com.logic.poly_.detail_;

public class PolyDetail03 {
    public static void main(String[] args) {
        //编译类型是BB 运行类型是BB
        BB bb = new BB();
        System.out.println(bb instanceof BB);
        System.out.println(bb instanceof AA);
        //编译类型是AA 运行类型是BB
        AA aa = new BB();
        System.out.println(aa instanceof AA);
        System.out.println(aa instanceof  BB);

        Object obj = new Object();
        System.out.println(obj instanceof AA);
        String str = "logic";
        System.out.println(str instanceof Object);
    }
}

class AA {} //父类
class BB extends AA{} //子类

多态练习

package com.logic.poly_.detail_;

public class PolyPractice {
    public static void main(String[] args) {
        double d = 13.4;//ok
        long i = (long)d;//ok
        System.out.println(i);//13
        int in = 5;//ok
        boolean b = (boolean)in;//不对 boolean -> int
        Object obj = "hello";//ok 向上转型
        String objStr = (String) obj;//ok 向下转型
        System.out.println(objStr);//hello
        
        Object objPri = new Integer(5);//ok 向上转型
        String str = (String) objPri;//不对 ClassCastException
        //指向Integer的父类引用 转成String
        Integer str1 = (Integer) objPri;//ok 向下转型
    }
}
package com.logic.poly_.detail_;

public class PolyPractice02 {
    public static void main(String[] args) {
        B b = new B();
        System.out.println(b.count);//20
        b.display();//20
        A a = b;
        System.out.println(a == b);//true
        System.out.println(a.count);//10
        a.display();//20
    }
}
class A {
    public int count = 10;

    public void display() {
        System.out.println(this.count);
    }
}
class B extends A {
    public int count = 20;

    public void display() {
        System.out.println(this.count);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值