Even for new Java developers, constructors are probably no big mystery. In essence, when you create an instance of a class, the constructor of this class is started. In the 6th part of Java Puzzlers series, we will see a case related to constructors.
public class Puzzler { public Puzzler(){ System.out.println("Puzzler no arg constructor"); } public static void main(String[] args){ Puzzler puzzler = new Puzzler(); } }In the example above Puzzler() constructor will start and "Puzzler no arg constructor" will be printed to the screen. Now lets see a new example.
public class Puzzler { public void Puzzler(){ System.out.println("Puzzler no arg constructor?"); } public static void main(String[] args){ Puzzler puzzler = new Puzzler(); } }As you can see we added a return value to the constructor of Puzzler and you may expect that "Puzzler no arg constructor?" will get printed but this is not right. When we add a return value to the constuctor, it stops being a constructor. So it won't get started when a new instance is created.