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
啊?
{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
啊?
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"就重写父类的方法,也就是我注释那段。