Pg188-3 构造方法
package org.hanqi.array; public class Father { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } // public Father() // { // System.out.println("父类的构造方法"); // } public Father(String name) { this.name=name; System.out.println("父类的有参的构造方法"); } public void work() { System.out.println("我劳动我光荣"); } }
package org.hanqi.array; public class Son extends Father { public Son() { super("儿子"); System.out.println("子类的构造方法"); } public void work() { super.work(); System.out.println("我边上班边练歌"); } }
package org.hanqi.array; public class TestJiCheng { public static void main(String[] args) { Father f=new Father("父亲"); //f.setName("父亲"); f.setAge(50); System.out.println("名字是:"+f.getName()+" 年龄是:"+f.getAge()); f.work(); System.out.println(); Son s=new Son(); //s.setName("儿子"); s.setAge(20); System.out.println("名字是:"+s.getName()+" 年龄是:"+s.getAge()); s.work(); } }
总结:构造子类时需要先构造父类,当需要调用父类的被覆盖的成员时,可以用super关键字调用