Last active
August 29, 2015 14:04
-
-
Save kenorb/d2004058dcef3a3b111d to your computer and use it in GitHub Desktop.
Constructor Demo in Java.
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
/* | |
* Constructor Demo. | |
* | |
* - Constructor is syntactically similar to a method, but it lacks of return type. | |
* - Constructor will have the same name as class name in which is declared. | |
* - Contructors are invoked immediately after creation of the objects. | |
* | |
* There are two types of constructors: | |
* - default constructor; | |
* - parameterised constructor; | |
* | |
* Note: | |
* If a class don't have explicit constructor, | |
* compiler will add a default constructor | |
* so that class can be instantiated. | |
* | |
* Note: | |
* If default constructor is missing, but parameterised constructor is defined, | |
* Java compiler will generate an error about mismatch. | |
* However if you don't write any constructor, | |
* compiler will add superclass constructor by it-self. | |
* So if you're adding parameterised constructor, always define default constructor. | |
*/ | |
class A { | |
A() { // Default constructor. | |
System.out.println("From default."); | |
} | |
A(int a, int b) { // Parameterised constructor. | |
System.out.println("From param constructor."); | |
System.out.println("a = " + a + "; b = " + b); | |
} | |
} | |
class ConstructorDemo { | |
public static void main(String[] args) { | |
new A(); // Invokes the default constructor. | |
new A(100, 200); // Invokes param constructor. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment