Java - Add Constructor to a class

A Cat Class with a Constructor

The Cat class declares a constructor.

Inside the constructor's body, it prints a message "Meow...".

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

Then the Main class creates two Cat objects in its main() method.

The first Cat object is created and its reference is not stored.

The second Cat object is created and its reference is stored in a reference variable c.

Demo

class Cat {
  public Cat() {//  w w  w  . j  a  v a 2 s.c  o m
    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();
  }
}

Result

Related Topic