Chinaunix

标题: 继承中的构造方法 [打印本页]

作者: studyj    时间: 2007-06-21 15:11
标题: 继承中的构造方法
继承中的构造方法

子类继承父类(基类)的构造方法

new 一个对象需要调用构造方法

对于一个子类  我们可以调用子类的构造方法 在子类中存在父类对象   需要调用父类的构造方法

子类对象构造过程中  应该首先调用父类的构造方法

调用的方式

super(参数列表)

父类的构造方法有很多个  可以重载  需要告诉test 你在调用哪一个

可以使用this() 来调用自己类的构造方法

如果调用了super 必须 写在子类构造方法的第一行 (构造子类前先构造父类)

(1) this
(2) super 这两个关键字的使用

如果没有写super 的话调用父类的构造方法(空的那个 无参的)

如果不写空的 会报错

必须调用父类构造方法

eg

调用过程

class Father{
private int age;
public Father(){
System.out.println("hello world is Father.");
}
public Father(int age){
this.age=age;
System.out.println("Father's age is "+age);
}
}
class Son extends Father{
private int age;
public Son(int age){
this.age=age;
System.out.println("Son's age is "+age);
}
public Son(){
System.out.println("Son's hello world");
}
}

class TestFun{
public static void main(String args[]){
Son s=new Son(20);
Son s2=new Son();
}
}

程序执行的结果:
hello world is Father.
Son's age is 20
hello world is Father.
Son's hello world

可以看到调用了父类的 无参的构造方法   


看得不太深刻 呵呵

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/40487/showart_325805.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2