class Father{
int x;
Father(){
x=3;
System.out.println("calling father:x="+x);
}
void doSomething(){
System.out.println("calling Father.doSomething()");
}
}
class Son extends Father{
int x;
Son()
{
super();
x=5;
System.out.println("calling Son:x="+x);
}
void doSomething(){
super.doSomething();
System.out.println("calling Son.doSomething");
System.out.println("Father.x="+super.x+" Son.x="+x);
}
}
public class SuperDemo{
public static void main(String args[]){
Son son=new Son();
son.doSomething();
}
}运行的时候为什么会出错??
int x;
Father(){
x=3;
System.out.println("calling father:x="+x);
}
void doSomething(){
System.out.println("calling Father.doSomething()");
}
}
class Son extends Father{
int x;
Son()
{
super();
x=5;
System.out.println("calling Son:x="+x);
}
void doSomething(){
super.doSomething();
System.out.println("calling Son.doSomething");
System.out.println("Father.x="+super.x+" Son.x="+x);
}
}
public class SuperDemo{
public static void main(String args[]){
Son son=new Son();
son.doSomething();
}
}运行的时候为什么会出错??
calling father:x=3
calling Son:x=5
calling Father.doSomething()
calling Son.doSomething
Father.x=3 Son.x=5没得问题
calling Son:x=5
calling Father.doSomething(
calling Son.doSomething
Father.x=3 Son.x=5
Press any key to continue..正常 鉴定完毕
public static void main(String args[]){
Son son=new Son();
son.doSomething();//这里的方法是子类的
}
}
calling Son:x=5
calling Father.doSomething()
calling Son.doSomething
Father.x=3 Son.x=5或者你能具体说说是什么错误提示吗?
我运行的也没有错
javac SuperDemo.java
java SuperDemo 在调用子类的构造方法时,会自动的调用父类的构造方法,但在调用子类的dosomeing()方法时,
不会自动的调用父类的dosomeing()方法,必须显示的调用super().dosomeing() ,在Son()方法
内的super()可以去掉.