super 和this的用法

class Person {

public static void prt(String s) {
System.out.println(s); // 打印出来结果
}

Person() {
prt("父类无参构造方法.");
}

Person(String name) {
prt("父类有参构造方法" + name);

}
}
public class superyongfa extends Person{
superyongfa() // 子类无参构造函数或构造方法
{
super(); // 调用父类构造函数(1)
prt("子类无参构造方法");// (4)
}

superyongfa(String name) {
super(name);// 调用父类具有相同形参的构造函数(2)
prt("子类一个元素构造方法" + name);
}

superyongfa(String name, int age) {
this(name);// 调用当前具有相同形参的构造函数(3)
prt("子类两个元素构造方法:" + age);
}

public static void main(String[] args)
{
superyongfa cn = new superyongfa();
cn = new superyongfa("kevin"); // 无论怎么样,先调用类的无参构造函数或方法,然后再调用相同参数的那个构造函数与方法

cn = new superyongfa("kevin", 22);// 但是有两个 superyongfa的话,就第一次 调用无参构造方法,第二次调用相同参数的
}

}

posted @ 2013-11-01 16:35  kin2321  阅读(256)  评论(0编辑  收藏  举报