Overloading a Constructor:Class with Two Constructors, One with No Parameter and One with a String Parameter - Java Object Oriented Design

Java examples for Object Oriented Design:Constructor

Description

Overloading a Constructor:Class with Two Constructors, One with No Parameter and One with a String Parameter

Demo Code

public class Main {
  public static void main(String[] args) {
    Dog d1 = new Dog();         // Uses Constructor #1
    Dog d2 = new Dog ("Canis"); // Uses Constructor #2
  }//from ww  w  . ja va2s  .com
}
class Dog {
  // Constructor #1
  public Dog() {
    System.out.println("A dog is created.");
  }

  // Constructor #2
  public Dog(String name) {
    System.out.println("A dog named " + name + " is created.");
  }
}

Result


Related Tutorials