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);
}
}