package org; public class Test { public static void main(String[] args) { A a = new B(); a.print(); } } class A { private int i = 1; public A() { int i = 2; } public void print() { System.out.println("The result is:" + i); } } class B extends A { private int i = 3; public B() { int i = 6; } public void print() { System.out.println("The result is:" + i); } }
输出结果是:3
此题考查的是多态.
在这里是父类的引用指向子类的对象.
父类的引用只能访问子类和父类共有的
方法.
这个程序我通过Eclipse和Debug程序观察它的
执行顺序是这样的:
package org; public class Test { public static void main(String[] args) { A a = new B(); a.print(); } } class A { //3 private int i = 1; //2 public A() { //4 int i = 2; } public void print() { System.out.println("The result is:" + i); } } class B extends A { //5 private int i = 3; //1 public B() { //6 int i = 6; } public void print() { System.out.println("The result is:" + i); } }
现在将程序稍微改动一下:
package org; public class Test { public static void main(String[] args) { A a = new B(); a.print(); } } class A { //3 private int i = 1; //2 public A() { //4 int i = 2; } public void print() { System.out.println("The result is:" + i); } } class B extends A { //5 private int i = 3; //1 public B() { //6 int i = 6; } public void print2() { System.out.println("The result is:" + i); } }
这时输出结果就是1了.
因为父类的引用无法访问子类独有的方法。