关于无参构造方法的补充案例

package p70_p72.f305_308.ch03;


class Student{

private int age;

String st0;

// public Student(){

// System.out.println("doing something in Student() - 1");

// }

public Student(int n,String st) {

age = n;

st0=st;

System.out.println("doing something in Student(int n) - 2");

}

}


class Stud extends Student{

int x;

public Stud(int x){

super(22,"stu001");//有了该调用,则父类无参数构造方法不影响子类构造方法,否则必须在父类定义无参构造方法。

this.x=x;

System.out.println("doing something in Stud Constructor 1");

}

}


public class Example308 {

public static void main(String[] args) {

//Student = new Student(); // 实例化 Student对象

Stud stemp=new Stud(10);

System.out.println("x="+stemp.x);

}

}

结论,如果子类构造方法第一条执行语句不是super(。。。),则父类必须包含无参构造方法(子类构造方法执行前会自动调用父类无参构造方法)。好的编程习惯是,一旦一个类定义了构造方法,至少因包含一个无参构造方法。

展开阅读全文

页面更新:2024-06-01

标签:方法   子类   语句   实例   结论   定义   对象   习惯   案例   参数   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top