Java - What is the output: constructor definition?

Question

What is the output of the following code?

class Cat {
  public void Cat() {
    System.out.println("Meow...");
  }
}

public class Main {
  public static void main(String[] args) {
    // Create a Cat object and ignore its reference
    new Cat();

    // Create another Cat object and store its reference in c
    Cat c = new Cat();
    
    System.out.println("Here");
  }
}


Click to view the answer

Here

Note

public void Cat() is not a constructor. It is normal method which happens to have the same name with class.

To make it a constructor you have to remove the void so that it does not have a return type.

Demo

class Cat {
  public Cat() {/*from  w  w  w .j a  v a 2 s  .c  om*/
    System.out.println("Meow...");
  }
}

public class Main {
  public static void main(String[] args) {
    // Create a Cat object and ignore its reference
    new Cat();

    // Create another Cat object and store its reference in c
    Cat c = new Cat();
    
    System.out.println("Here");
  }
}

Result

Related Quiz