class A { PRotected void print(String s) { System.out.println(s); } A() { print("A()"); } public void f() { print("A:f()"); }}class B extends A { B() { print("B()"); } public void f() { print("B:f()"); } public static void main(String[] args) { B b = new B(); b.f(); }}運行結果:
A()B()B:f()正好印證了第一點:子類在new一個對象時,會先在構造方法中調用父類的構造方法。二、子類可以在自己的構造方法中使用super(argument_list)調用父類的構造方法。 1)如果調用super,必須寫在子類構造方法的第一行。2)使用this(argument_list)調用本類其它的構造方法。
class Person { private String name; private String location; Person(String name) { this.name = name; location = "beijing"; } Person(String name, String location) { this.name = name; this.location = location; } public String info() { return "name: " + name + " location: " + location; }}class Student extends Person { String school; Student(String name, String school) { this(name, "beijing", school); } Student(String name, String location, String school) { super(name, location); this.school = school; } public String info() { return super.info() + " school: " + school; }}public class Test { public static void main(String[] args) { Person p1 = new Person("A"); Person p2 = new Person("B", "shanghai"); Student s1 = new Student("C", "S1"); Student s2 = new Student("C", "shanghai", "S2"); System.out.println(p1.info()); System.out.println(p2.info()); System.out.println(s1.info()); System.out.println(s2.info()); }} 運行結果:
name: A location: beijingname: B location: shanghainame: C location: beijing school: S1name: C location: shanghai school: S2正好印證了第二點:子類可以在自己的構造方法中使用super(argument_list)調用父類的構造方法,super構造方法必須是子類構造方法的第一條語句,子類構造方法可以使用this(argument_list)來調用本類其它的構造方法。
本例中的一些構造方法自動給沒有傳進來的參數進行了默認值的賦值,如location = "beijing";這是在new對象時還不確定location值為多少的情況下的一種暫定為、默認為"beijing"的處理。
三、如果子類的構造方法沒有顯式地調用父類構造方法(即未調用super(argument_list)),則系統調用父類無參數的構造方法。
class Person { String name; Person() { System.out.println("Person"); }}class Student extends Person{ String school; Student(String school) { this.school = school; }}如果子類Student構造方法的第一條語句缺省super,系統將自動調用父類無參的構造方法Person()。四、如果子類構造方法中既沒有顯式地調用父類構造方法,而父類中又沒有無參的構造方法,則編譯出錯。class Person { String name; Person(String name) { this.name = name; }}class Student extends Person{ String school; Student(String school) { this.school = school; }}如果是這種情況,別指望系統能夠調用父類無參的構造方法。一旦構造方法被重載,并且沒有重載出無參的構造方法,那么該類中就沒有無參的構造方法了,此例的父類Person就是如此,因此在編譯時就會報錯。
新聞熱點
疑難解答