PHP [] [] java difference between the execution parent class constructor

  • PHPIf there is a subclass constructor will not go call the constructor of the parent class, if the constructor of a subclass is empty, then take the call the parent, if the parent class constructor is empty, then the transfer of Father parent class constructor, and so on, directly to the default constructor
  • JAVASubclasses always call the constructor of the parent class, regardless of whether there is a subclass constructor (generally), if the code is not a subclass of parent class constructor call, that call is no default argument constructor of the parent class function (implicit call), if it is multiple inheritance, an implicit call will be very long

Attach test code *** ***

<?php

class A {
    function __construct()
    {
        echo 33;
    }
}

class B extends A{
//    function __construct()
//    {
//        echo 22;
//    }
}

class C extends  B{
//    function __construct()
//    {
//        echo  11;
//    }
}

new C();
class BaseClass {
    BaseClass() {
        System.out.println("HELLO");
    }
}

class SuperClass extends BaseClass{
    private int n;
    SuperClass(){
        System.out.println("SuperClass()");
    }
    SuperClass(int n) {
        System.out.println("SuperClass(int n)");
        this.n = n;
    }
}
// SubClass 类继承
class SubClass extends SuperClass{
    private int n;

    SubClass(){ // 自动调用父类的无参数构造器
        System.out.println("SubClass");
    }

    public SubClass(int n){
        super(300);  // 调用父类中带有参数的构造器
        System.out.println("SubClass(int n):"+n);
        this.n = n;
    }
}
// SubClass2 类继承
class SubClass2 extends SuperClass{
    private int n;

    SubClass2(){
        super(300);  // 调用父类中带有参数的构造器
        System.out.println("SubClass2");
    }

    public SubClass2(int n){ // 自动调用父类的无参数构造器
        System.out.println("SubClass2(int n):"+n);
        this.n = n;
    }
}
public class TestSuperSub{
    public static void main (String args[]){
        System.out.println("------SubClass 类继承------");
        SubClass sc1 = new SubClass();
        SubClass sc2 = new SubClass(100);
        System.out.println("------SubClass2 类继承------");
        SubClass2 sc3 = new SubClass2();
        SubClass2 sc4 = new SubClass2(200);
    }
}

NOTE: java novice tutorial test reference code portion (it is noted)

Guess you like

Origin www.cnblogs.com/china-flint/p/11389584.html