Created
August 20, 2019 08:13
-
-
Save l0co/fba43e2b11f686a368cb4d250608bcd8 to your computer and use it in GitHub Desktop.
Java constructor calling rules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class JavaConstrcutor { | |
public static class A { | |
public A() { | |
System.out.println("A"); | |
} | |
public A(String message) { | |
System.out.println("A:"+message); | |
} | |
} | |
public static class B extends A { | |
public B() { | |
System.out.println("B"); | |
} | |
public B(String message) { | |
System.out.println("B:"+message); | |
} | |
public B(String message, boolean dummy) { | |
super(message); | |
System.out.println("B:"+message); | |
} | |
} | |
public static void main(String[] args) throws IOException { | |
// A | |
new A(); | |
System.out.println("-----------"); | |
// A:hello | |
// (default constructor is not called by default) | |
new A("hello"); | |
System.out.println("-----------"); | |
// A | |
// B | |
// (default constructor is called by default from superclass when no super() is used) | |
new B(); | |
System.out.println("-----------"); | |
// A | |
// B:hello | |
// (default constructor is called by default from superclass when no super() is used, even for non-default subclass constrcutor) | |
new B("hello"); | |
System.out.println("-----------"); | |
// A:hello | |
// B:hello | |
// (if super() is used, the default constructor from superclass is not called) | |
new B("hello", true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment