继承中的构造方法——super关键字
TestSuperSub.java
//继承中的构造方法——super关键字 class SuperClass { private int n; SuperClass() { System.out.println("父类无参构造方法SuperClass()"); } SuperClass(int n) { System.out.println("父类有参构造方法SuperClass(" + n + ")"); this.n = n; } } class SubClass extends SuperClass { private int n; //子类的构造过程必须调用其父类(基类)的构造方法 SubClass(int n) { /* 如果调用super必须写在子类构造方法的第一行 如果子类的构造方法中没有显示的调用父类的构造方法,则默认调用基类的无参构造方法 如果子类的构造方法中既没有显示调用父类的构造方法,父类也没有无参构造方法,则编译出错 */ //super(); System.out.println("子类有参构造方法SubClass(" + n + ")"); this.n = n; } SubClass() { super(300); System.out.println("子类无参构造方法SubClass()"); } } public class TestSuperSub { public static void main(String arg[]) { //SubClass sc1 = new SubClass(); SubClass sc2 = new SubClass(400); } }
构造方法和一般成员方法在继承中的区别
Sub.java
//构造方法和一般成员方法在继承中的区别 class A { protected void print(String str) { System.out.println(str); } A(){ print("A()"); } public void f() { print("A:f()"); } } class B extends A { B(){ print("B()"); } //重写A中的f() public void f() { print("B:f()");j } } public class Sub { public static void main(String[] args) { B b = new B(); b.f(); /* 结果: A() B() B:f() 分析结果,体会构造方法和一般成员方法在继承中的区别 */ } }
简单的练习,使用super关键字,以及继承中的构造方法,方法的重写Override
TestPer.java
//简单的练习,使用super关键字,以及继承中的构造方法,方法的重写Override class Person { private String name; //姓名 private String location; //地址 Person(String name) { this.name = name; location = "北京"; } Person(String name, String location){ this.name = name; this.location = location; } public String info() { return "name: " + name + ";location: " + location; } } class Student extends Person { private String school; //学校 Student(String name, String school) { this(name,"北京",school); } Student(String n, String l, String s) { super(n,l); this.school = s; } //重写Override info()方法 public String info() { return super.info() + ";school: " + school; } } class Teacher extends Person { private String capital; //职称 Teacher(String name, String capital) { this(name, "广州", capital); } Teacher(String n, String l, String capital) { super(n, l); this.capital = capital; } public String info() { return super.info() + ";capital: " + capital; } } public class TestPer { public static void main(String[] args) { Person p1 = new Person("A"); Person p2 = new Person("B","上海"); Student s1 = new Student("C","第一实验小学"); Student s2 = new Student("D","武汉","第二实验小学"); System.out.println(p1.info()); //name: A;location: 北京 System.out.println(p2.info()); //name: B;location: 上海 System.out.println(s1.info()); //name: C;location: 北京;school: 第一实验小学 System.out.println(s2.info()); //name: D;location: 武汉;school: 第二实验小学 Teacher t1 = new Teacher("E", "教授"); System.out.println(t1.info()); //name: E;location: 广州;capital: 教授 } }