package test;
class Base {
int x = 1;
static int y = 2;
int z = 3;
int method() {
return x;
}
}
class Subclass extends Base {
int x = 4;
int y = 5;
static int z = 6;
int method() {
return x;
}
}
public class PolymorphismTest1 {
public static void main(String[] args) {
Base bs = new Subclass();
System.out.println("bs.x:"+bs.x + " bs.y:" + bs.y + " bs.z:" + bs.z);
System.out.println("bs.method:"+bs.method());
System.out.println("================================");
Base bb = new Base();
System.out.println("bb.x:"+bb.x + " bb.y:" + bb.y + " bb.z:" + bb.z);
System.out.println("bb.method:"+bb.method());
System.out.println("================================");
Subclass ss = new Subclass();
System.out.println("ss.x:"+ss.x + " ss.y:" + ss.y + " ss.z:" + ss.z);
System.out.println("ss.method:"+ss.method());
System.out.println("================================");
Subclass sb = (Subclass)new Base();//Exception in thread "main" java.lang.ClassCastException: test.Base
//System.out.println("sb.x:"+sb.x + " sb.y:" + sb.y + " sb.z:" + sb.z);
//System.out.println("sb.method:"+sb.method());
//System.out.println("================================");
}
}
=======================
结果:
=======================
bs.x:1 bs.y:2 bs.z:3
bs.method:4
================================
bb.x:1 bb.y:2 bb.z:3
bb.method:1
================================
ss.x:4 ss.y:5 ss.z:6
ss.method:4
================================