class Fa
{String x="father";
 void print()
 {System.out.println(x);};
}
class Son extends Fa
{String x="son";}
public class T1
{public static void main(String args[])
 {
  Son x2=new Son();
  Fa x1=new Fa();
  
  x1.print();
  x2.print();
 }
}
结果是:
father
father
为什么不是:
father
son
啊?

解决方案 »

  1.   

    class Father {
    String x = "father"; void print() {
    System.out.println(x);
    }
    }class Son extends Father {
    String x = "son";
    /*void print() {
    System.out.println(x);
    }*/
    }public class Test {
    public static void main(String args[]) {
    Father x1 = new Father();
    Son x2 = new Son(); x1.print();
    x2.print();
    }
    }你的son类继承Father类,父类里有print()方法而子类里没有,所以你子类对象调用print()方法是实际是调用从父类继承下来的。想输出"son"就重写父类的方法,也就是我注释那段。
      

  2.   

    son类继承Father类之后,它不是也继承父类的print()方法吗?
      

  3.   

    son类继承Father类之后,它不是也继承父类的print()方法吗?没错,但是,虽然你的子类隐藏了父类的变量,但是由于print方法的入口还是在父类,而父类中又自己有变量x,这样它调用的还是父类的x,而不是子类的x
      

  4.   

    你的son类继承Father类,父类里有print()方法而子类里没有,所以你子类对象调用print()方法是实际是调用从父类继承下来的。想输出"son"就重写父类的方法,也就是我注释那段。