class   Person   { 
//         private 
        String   name; 
//         private 
        int   age; 
        public   Person()   { 
                System.out.println("调用了person的构造方法"); 
        }         public   Person(String   name,   int   age)   { 
                this.name   =   name; 
                this.age   =   age;         }         public   void   show()   { 
                System.out.println("姓名:   "   +   name   +   "   年龄:   "   +   age); 
        } } 
class   student   extends   Person   { 
        private   String   department; 
        public   student()   { 
                System.out.println("调用了无参构造方法Student()"); 
        }         public   student(String   name,   int   age,   String   dep)   { 
          1。       //   super(name,age);                         //如果省略此句,父类无参数构造方法仍然被调用 
            2。     //         this.name=name;                       //可传递参数 
            3。     //         this.age=age; 
          4。   //     new   Person(name,   age);//   **************//为什么不可以传递参数******************* 
                this.department   =   dep; 
                System.out.println("我是"   +   department   +   "的学生"); 
                System.out.println("调用了学生里的构造方法Student(String   dep)");   
        } 

该程序中用红色标记的第一行去掉注释,也就是最标准的程序结果为:调用了person的构造方法 
调用了无参构造方法Student() 
我是信息的学生 
调用了学生里的构造方法Student(String   dep) 
姓名:   null   年龄:   0 
姓名:   张三   年龄:   23 
第2,3行去掉注释,注释掉第一行 
结果:   调用了person的构造方法 调用了无参构造方法Student() 调用了person的构造方法 我是信息的学生 调用了学生里的构造方法Student(String   dep) 姓名:   null   年龄:   0 姓名:   张三   年龄:   23 
注释掉1,2,3把第4行去掉注释,结果 调用了person的构造方法 调用了无参构造方法Student() 调用了person的构造方法 我是信息的学生 调用了学生里的构造方法Student(String   dep) 姓名:   null   年龄:   0 姓名:   null   年龄:   0 
问: 
super()是调用父类的有参构造方法,那么为什么用new   就不可以传递参数呢?如果不用“this.”传递参数也不用super,如何通过调用父类传递参数? 为什么调用子类构造方法自动调用父类无参构造方法,而用super则不调用父类无参构造方法,super和new   +父类构造方法有何区别? 

解决方案 »

  1.   


    public class SonTest
    {
    public static void main(String[] args) 
    {
    Son son = new Son(3);
    System.out.println(son.getNum());
    }
    }
    class Father 
    {
    private int num;
    public Father()
    {
    this.num = 5;
    }
    public Father(int n)
    {
    this.num = n;
    }
    public int getNum()
    {
    return num;
    }
    }class Son extends Father
    {
    public Son()
    {
    System.out.println("Son with no args");
    }
    public Son(int n)
    {
    System.out.println("Son with args");
    //super(n);
    }
    public int getNum()
    {
    return super.getNum();
    }
    }
      

  2.   

    首先 Son son = new Son(3); 或者 Son son = new Son();
    实例化一个子类的时候肯定调用父类的构造函数的,父类的构造函数处理子类从父类继承过来的实例变量。在上例中,编译运行可以得到"Son with args 3",而在public Son(int n)中我们写不写super(n)是一样的。其次 当
        public Father(int n)
        {
            this.num = n;
        }
    被注释时候,编译运行显示 "Son with args 5”,这样son构造时显然是调用了Father类的public Father()来初始化实例变量。最后在你的例子中在构造函数中 public Son(){ new Son();} 不知道是要干什么?