java 中super和this 的一些應用

public class ExtendsSuperAndThis {


public static void main(String[] args) {
// TODO Auto-generated method stub
Father f = new Father();//我是父類中的無參數構造方法
Son s = new Son();// 我是父類中的無參數構造方法 ,我是子類中的無參數構造方法  默認調用父類 中無參數構造方法。
System.out.println(f.name);//張三
System.out.println(s.name);//李四
s.say();//我是李四,張三他兒子
f.say();//我是張三

Son s1 = new Son("hello",70);//調用父類中有參數的構造方法:我是父類中的有參數構造方法,我是子類中的有參數構造方法2

}


}
class Father{
String name = "張三";
String add;
double height;
double weight;

public void say() {
System.out.println("我是張三");
}

public Father() {
super();
System.out.println("我是父類中的無參數構造方法");
}


public Father(String name, String add, double height, double weight) {
super();
this.name = name;
this.add = add;
this.height = height;
this.weight = weight;
System.out.println("我是父類中的有參數構造方法");
}


}
class Son extends Father{
String name = "李四";
String add;
double height;
double weight;
String school;
public void say() {
System.out.println("我是李四,張三他兒子");
}

public Son() {
super();
System.out.println("我是子類中的無參數構造方法");
}

public Son(String school) {
this();//調用本參數中的構造方法
this.school = school;
System.out.println("我是子類中的有參數構造方法1");
}

public Son(String school,double weight) {
super("王五","北京",180,60);
this.school = school;
this.weight = weight;
System.out.println("我是子類中的有參數構造方法2");
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章