Java代码
- class Parent {
- int i = 1;
- String j = "Parent J";
- StringBuffer k = new StringBuffer("Parent:");
- public String getJ() {
- return j;
- }
- public int getI() {
- return i;
- }
- public void printBuffer() {
- k.append("Parent Buffer;");
- System.out.println(k);
- }
- static String getClassName() {
- return "Parent";
- }
- }
- class Child extends Parent {
- int i = 2;
- String j = "Child J";
- StringBuffer k = new StringBuffer("Child:");
- public String getJ() {
- return j;
- }
- public int getI() {
- return -i;
- }
- public void printBuffer() {
- k.append("Child Buffer;");
- System.out.println(k);
- }
- static String getClassName() {
- return "Child";
- }
- } </span>
- <span style="font-size: small;">public class ExtendDemo {
- public static void main(String[] args) {
- Child child = new Child();
- System.out.println("Child type test:");
- System.out.println("child.i:" + child.i);
- System.out.println("child.getI():" + child.getI());
- System.out.println("child.j:" + child.j);
- System.out.println("child.getJ():" + child.getJ());
- child.printBuffer();
- System.out.println("child.getClassName():" + child.getClassName());
- System.out.println();
- Parent parent = child;
- System.out.println("Parent type test:");
- System.out.println("parent.i:" + parent.i);
- System.out.println("parent.getI():" + parent.getI());
- System.out.println("parent.j:" + parent.j);
- System.out.println("parent.getJ():" + parent.getJ());
- parent.printBuffer();
- System.out.println("parent.getClassName():" + parent.getClassName());
- }
- } </span>
运行结果如下:
Child type test:
child.i:2
child.getI():-2
child.j:Child J
child.getJ():Child J
Child:Child Buffer;
child.getClassName():Child
Parent type test:
parent.i:1
parent.getI():-2
parent.j:Parent J
parent.getJ():Child J
Child:Child Buffer;Child Buffer;
parent.getClassName():Parent
Child继承Parent,子类的变量和静态方法分别隐藏父类的变量和静态方法,子类的实例方法覆盖父类的实例方法。隐藏只是把父类的东东藏起来,但是其还是实质存在的;而覆盖就是把父类的东东完全抹掉以替换成子类的,是不可恢复的。在child被强制转换成Parent类型后,被隐藏的东西又被恢复了,而被覆盖的方法却是一去不复返了(子类的方法在这个实例里面永久替代了原先父类的方法)。这就是区别,也是这个题的考点所在了。