Java- Constructors

class Constructors {
public static void main(String[] args) {
Greet g = null;//local variable should be initialized before use
if (args.length != 0) {
g = new Greet(args[0]);
} else {/*provided to avoid NullPointerException when no command line
argument is given*/
g = new Greet();
}
g.showGreeting();

}
}

class Greet {
private String name = "Anonymous";

Greet() {//provided to ensure the success of g = new Greet();
}/*if not given:
cannot find symbol
symbol : constructor Greet()*/

Greet(String name) {
/*refining the scope of instance variable name using the predefined reference variable this since, its direct usage refers only to the local variable name*/
this.name = name;
}

void showGreeting() {
System.out.println("Hi " + name + "!!!");
}
}

Case Study:
java Constructors
Hi Anonymous!!!

java Constructors uce
Hi uce!!!

Note: Default constructor is provided by the Java Virtual Machine (JVM) only when a class does not have one of its own.

Post a Comment

0 Comments