首先子类不能调用父类的初始化方法,但可以调用父类的void方法。当子类调用父类方法会自动先执行父类的默认初始化方法,然后执行调用方法。public class father { String f; public father(){ System.out.println("父类,无参。"); } public void father(String f){ this.f = f; System.out.println("父类,有参:"+f); } } public class son extends father{ public static void main(String args[]){ son s = new son(); //s.father("Hello"); } }自己执行一次就可以知道了
class father { String f; public father(){ System.out.println("父类,无参。"); } public father(String f){ this.f = f; System.out.println("父类,有参:"+f); } } public class son extends father{ son(){ super("父类方法"); } public static void main(String args[]){ son s = new son(); // s.father("Hello"); } }结果是:父类,有参:父类方法,没有执行father默认的初始化方法呀
class Test_1{ Test_1(){ System.out.println("无参数"); } Test_1(int i){ System.out.println("有参数"+i); } } public class Test_2 extends Test_1{ Test_2(){ super(2); } public static void main (String[] args){ Test_2 test = new Test_2(); } } 结果是:不会
想这位一样print一下就知道了,有些时候不能光想,动手才会有结果,才能记得更劳。
class Test_1{ Test_1(){ System.out.println("无参数"); } Test_1(int i){ System.out.println("有参数"+i); } } public class Test_2 extends Test_1{ Test_2(){ super(2); } public static void main (String[] args){ Test_2 test = new Test_2(); } } 结果不会的
public father(){
System.out.println("父类,无参。");
} public void father(String f){
this.f = f;
System.out.println("父类,有参:"+f);
}
}
public class son extends father{
public static void main(String args[]){
son s = new son();
//s.father("Hello");
}
}自己执行一次就可以知道了
public father(){
System.out.println("父类,无参。");
} public father(String f){
this.f = f;
System.out.println("父类,有参:"+f);
}
}
public class son extends father{
son(){
super("父类方法");
}
public static void main(String args[]){
son s = new son();
// s.father("Hello");
}
}结果是:父类,有参:父类方法,没有执行father默认的初始化方法呀
Test_1(){
System.out.println("无参数");
}
Test_1(int i){
System.out.println("有参数"+i);
}
}
public class Test_2 extends Test_1{
Test_2(){
super(2);
}
public static void main (String[] args){
Test_2 test = new Test_2();
}
}
结果是:不会
想这位一样print一下就知道了,有些时候不能光想,动手才会有结果,才能记得更劳。
Test_1(){
System.out.println("无参数");
}
Test_1(int i){
System.out.println("有参数"+i);
}
}
public class Test_2 extends Test_1{
Test_2(){
super(2);
}
public static void main (String[] args){
Test_2 test = new Test_2();
}
}
结果不会的