Saturday, May 9, 2020

java puzzlers from oca part 6


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.
01public class Puzzler {
02 
03    public Puzzler(){
04        System.out.println("Puzzler no arg constructor");
05    }
06 
07    public static void main(String[] args){
08        Puzzler puzzler = new Puzzler();
09    }
10}
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.
01public class Puzzler {
02 
03    public void Puzzler(){
04        System.out.println("Puzzler no arg constructor?");
05    }
06 
07    public static void main(String[] args){
08        Puzzler puzzler = new Puzzler();
09    }
10}
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.

3 comments:

  1. The "return" is missing - Copy&Paste got you ;-)
    Nevertheless, nice puzzler, which you normally don't think about. Thank you!
    Markus

    ReplyDelete
    Replies
    1. Thanks Markus. By "we added a return value" I meant that we added "void" to public Puzzler. There is no real return value for none of these methods.

      Delete
    2. You changed the constructor to a method. So the default implicit no-arg is called instead.

      Delete