Java Overload

A method that exists in the same class has the same name as an existing method but has at least one different parameter type, number, and order.

It should be noted that if the return value is different and everything else is the same it’s not an overload.

The instance

class A { public String show(D obj) { return (“A and D”); }

public String show(A obj) {
    return ("A and A");
}
Copy the code

}

class B extends A { public String show(B obj) { return (“B and B”); }

public String show(A obj) {
    return ("B and A");
}
Copy the code

}

class C extends B { }

class D extends B { } public class Test {

public static void main(String[] args) {
    A a1 = new A();
    A a2 = new B();
    B b = new B();
    C c = new C();
    D d = new D();
    System.out.println(a1.show(b)); // A and A
    System.out.println(a1.show(c)); // A and A
    System.out.println(a1.show(d)); // A and D
    System.out.println(a2.show(b)); // B and A
    System.out.println(a2.show(c)); // B and A
    System.out.println(a2.show(d)); // A and D
    System.out.println(b.show(b));  // B and B
    System.out.println(b.show(c));  // B and B
    System.out.println(b.show(d));  // A and D
}
Copy the code

}

When it comes to overwriting, the priority of a method call is:

this.show(O) super.show(O) this.show((super)O) super.show((super)O)

The initialization order of variables and methods in Java

Static variables and static statement blocks take precedence over instance variables and normal statement blocks, and the order in which they are initialized depends on the order in which they are placed in the code.

Public static String staticField = “static “; Static {system.out.println (” static statement block “); } public String field = “instance “; {system.out.println (” plain statement block “); }

Finally, the constructor is initialized.

Public InitialOrderTest() {system.out.println (” constructor “); }

In the case of inheritance, the initialization sequence is:

Parent class (static variable, static statement block) Subclass (static variable, static statement block) Parent class (Instance variable, ordinary statement block) Subclass (constructor) Subclass (instance variable, ordinary statement block) Subclass (constructor)