Precautions for JAVA inheriting the super keyword to call the parent class constructor
1. When a subclass creates an object, it will call the constructor of the parent class first by default.
2. The reason is that super() exists in the first line of the subclass constructor by default; – means calling the no-argument construction of the parent class
3. When the parent class does not have a parameterless structure, you can use super (parameter); to manually call other parameter-containing structures of the parent class
Note: A subclass must call a constructor of the parent class, whether it is without parameters or with parameters, just choose one
4. The super call constructor must be in the first line of the constructor 1
5. The construction method cannot be inherited! Reason: Because the required method name of the constructor must be the class name of this class, a constructor with the name of the parent class cannot appear in the subclass
package cn.tedu.oop3;
/**本类用于测试super的用法
* 1.子类在创建对象时,默认会先调用父类的构造方法
* 2.原因是子类构造函数中的第一行默认存在super();--表示调用父类的无参构造
* 3.当父类没有无参构造时,可以通过super(参数);手动调用父类的其他含参构造
* 注意:子类必须调用父类的是一个构造函数,不管是无参还是含参,选一个即可
* 4.super调用构造函数要求必须在构造函数的第1行1
* 5.构造方法不可以被继承!原因:因为构造函数的要求方法名必须是本类的类名
* 不能在子类中出现一个父类名字的构造方法*/
public class TestSuper2 {
public static void main(String[] args){
//5.触发父类的两个构造函数创建对象
// Father2 f1 =new Father2();//触发父类的无参构造
Father2 f2 =new Father2(88);//触发父类的含参构造
//6.创建子类对象进行测试
Son2 s = new Son2();}}
//1.创建父类
class Father2{
//3.创建父类无参构造与含参构造
// public Father2(){
// System.out.println("我是父类的无参构造");
// }
public Father2(int n){
System.out.println("我是父类的含参构造"+n);}}
//2.创建子类
class Son2 extends Father2{
//4.创建子类的无参构造
public Son2(){
// super();//表示调用父类的无参构造
super(99);//表示父类的含参构造
System.out.println("子类的无参构造");}}