如果有个子类:Sub和一个父类:Super,
在Super的父类中只有一个构造函数是Super(int i){}
若要在子类中的构造函数显示地调用父类的构造函数要怎么写呢??
import static java.lang.System.*;
public class Main{
public static void main (String[] args) {
SubClass sub=new SubClass();
}
}
class Sub extends Super{
int i=m1();
int m1(){
out.println("m1");
return 1;
}
Sub(){
    Super(5);
    out.println("调用子类构造函数");
}
}
class Super{
int k;
int j=m2();
int m2(){
out.println("m2");
return 2;
}
Super(int l){
             k=l;
}}
这样写错在哪里呢- -

解决方案 »

  1.   

    不知道楼主是不是想要这种效果?父类中有带参的构造方法,子类中是必须要有一个带参方法的public class Sub extends Super{ Sub(int l) {
    super(l);
    System.out.println("调用子类构造函数");
    }
    int i=m1();
    int m1(){
    System.out.println("m1");
    return 1;
    }
    }public class Super {
    int k;
    int j=m2();
    int m2(){
    System.out.println("m2");
    return 2;
    }

    Super(int l){
      System.out.println("调用父类构造函数");
      k=l;
    }
    }public class Exct7 { public static void main(String[] args) {
    Sub sub=new Sub(5); }
    }
      

  2.   

    意思是说 父类中只有带参数的构造函数,而在实例化子类的时候不是要调用父类的构造函数么?要怎么显示调用才对?
    还有个问题就是在子类的构造函数中调用父类的构造函数不用new 父类类名()这种形式调用么??
      

  3.   

    (1)父类只有带参构造函数,那么就没有默认的无参构造函数了,如果需要,得自己写
    (2)调用父类的带参构造函数,只要在子类的构造函数中写上super(args1,...)就可以了
    (3)new 的作用是生成一个对象,而不是调用函数
      

  4.   

     直接用super关键字就ok了 
      

  5.   

    Sub(int l){
    Super(5);
    }
    这样啊??
    还是其他的写法??
      

  6.   

    Sub(int i){
    super(5);
    }
    这里的super是关键字,不是父类的Super
      

  7.   

    通过测试:
    1.如果父类和子类都只有默认构造函数,那么super()就不用说了
    2.如果父类只有默认构造函数,子类有默认构造函数和自定义的构造函数,那么不管你用没用super(),new B()都会去调用父类的默认构造函数,两个都一样会
    3.如果父类只有自定义的构造函数,那么子类中出现默认构造函数就会出错,只能在子类中super()父类的构造函数。
    4.如果父类和子类都有默认和自定义构造函数的话,这个就不用说了吧。楼主可以自己去测试下,10分钟都不要。给你我部分测试代码吧:
    1.第二种情况测试//父类
    public class A {

    public A(){

    System.out.println("this is the method in A");

    }
    }//子类
    public class B extends A {

    public B(){

    System.out.println("this is the method in B");
    }
    public B(int i){

    System.out.println("this is the method in B,and I have a i and i="+i);
    }}//调用
    public class Test { /**
     * @param args
     */
    public static void main(String[] args) {
    B b1=new B();
    System.out.println();
    B b2=new B(5);
    }}
    //结果
    this is the method in A
    this is the method in Bthis is the method in A
    this is the method in B,and I have a i and i=5
    第三部分测试:public class A {

    public A(int i){

    System.out.println("this is the method in A,and I have a value i,and i="+i);

    }

    }
    public class Test { /**
     * @param args
     */
    public static void main(String[] args) {

    B b2=new B(5);
    }}
    //结果:
    this is the method in A,and I have a value i,and i=5