第一点
public class Waring { public static void main(String[] args) { //属性没有重写之说!属性的值看编译类型
//编译类型是base
Base base = new Sub();//向上转型
System.out.println(base.count);// ? 看编译类型 10
//编译类型是sub
Sub sub = new Sub();
System.out.println(sub.count);//? 20
}
}
class Base { //父类 int count = 10;//属性 }
class Sub extends Base {//子类 int count = 20;//属性 }
![image.png](https://cdn.nlark.com/yuque/0/2021/png/21705001/1638541554918-6602839d-825f-4a4c-bac8-0bfd5691fc09.png#clientId=u0b376ae9-bb67-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=203&id=u3b343a01&margin=%5Bobject%20Object%5D&name=image.png&originHeight=167&originWidth=616&originalType=binary&ratio=1&rotation=0&showTitle=false&size=14242&status=done&style=none&taskId=u31be4e7c-6ca0-4e2d-a79b-28f5bbc8bf5&title=&width=750)
<a name="Kdggo"></a>
## 案例二:
```java
public class Waring02 {
public static void main(String[] args) {
//编译类型是Sub
Sub s = new Sub();
//看编译类型
System.out.println(s.count);//20
//看运行类型
s.display();//20
//编译类型是Base
Base b = s;
System.out.println(b == s);//T
//看编译类型
System.out.println(b.count);//10
b.display();//20
}
}
class Base {//父类
int count = 10;
public void display() {
System.out.println(this.count);
}
}
class Sub extends Base {//子类
int count = 20;
@Override
public void display() {
System.out.println(this.count);
}
}
第二点
- instanceOf比较操作符,用于判断对象的运行类型是否为XX类型或者XX类型的子类型 ```java package detail;
public class Waring01 { public static void main(String[] args) { BB bb = new BB(); System.out.println(bb instanceof BB);// true System.out.println(bb instanceof AA);// true
//aa 编译类型 AA, 运行类型是BB
//BB是AA子类
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);//false
String str = "hello";
//System.out.println(str instanceof AA);//报错!!!
System.out.println(str instanceof Object);//true
}
}
class AA {//父类 }
class BB extends AA {//子类 } ```