Java - Initialize Instance Variables Differently

Introduction

You can use overloaded to constructor to Initialize Instance Variables Differently.

The following code creates a Cat Class That Declares Two Constructors to Initialize Instance Variables Differently.

The default constructor is as follows

Initialize the name to "Unknown" and the price to 0.0

public Cat() {
    
    this.name = "Unknown";
    this.price = 0.0;

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

The second constructor initializes name and price instance variables with the name and price parameters.

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");
}

Demo

class Cat {
  private String name;
  private double price;

  public Cat() {/*w ww  . j  a va2s  . c o  m*/
    // Initialize the name to "Unknown" and the price to 0.0
    this.name = "Unknown";
    this.price = 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