Java - Class Reuse constructor

Introduction

The following code shows how to reuse a constructor.

The first constructor initializes the name and the price with default values.

public Cat() {
    // Initialize the name to "Unknown" and the price to 0.0
    this("Unknown", 0.0);
    System.out.println("Using Cat() constructor");
}
  

The second constructor lets you initialize name and price with the value supplied by the caller.

Initialize name and price instance variables with the name and price parameters

public Cat(String name, double price) {
    this.name = name;
    this.price = price;

    System.out.println("Using Cat(String, double) constructor");
}
  

Demo

class Cat {
  private String name;
  private double price;

  public Cat() {/*from w w  w. j  av a 2 s .  c o  m*/
    // Initialize the name to "Unknown" and the price to 0.0
    this("Unknown", 0.0);
    System.out.println("Using Cat() constructor");
  }
  public Cat(String name, double price) {
    // Initialize name and price instance variables
    // with the name and price parameters
    this.name = name;
    this.price = price;

    System.out.println("Using Cat(String, double) constructor");
  }


  public void talk() {
    System.out.println(name + " is talking...");
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return this.name;
  }

  public void setPrice(double price) {
    this.price = price;
  }

  public double getPrice() {
    return this.price;
  }

  public void printDetails() {
    System.out.print("Name: " + this.name);
    if (price > 0.0) {
      System.out.println(", price: " + this.price);
    } else {
      System.out.println(", price: Free");
    }
  }
}

public class Main {
  public static void main(String[] args) {
    // Create two SmartDog objects
    Cat sd1 = new Cat();
    Cat sd2 = new Cat("Cute", 1234.5);

    // Print details about the two dogs
    sd1.printDetails();
    sd2.printDetails();

    // Make them talk
    sd1.talk();
    sd2.talk();

    // Change the name and price of Unknown cat
    sd1.setName("New Name");
    sd1.setPrice(4321.0);

    // Print details again
    sd1.printDetails();
    sd2.printDetails();

    // Make them bark one more time
    sd1.talk();
    sd2.talk();
  }
}

Result

Related Topic