Java Constructors Overloading.

Java Constructors Overloading

  • A constructor can invoke another constructor (overloaded) in its class using the self-referential method call this().
  • You must support the this() method with appropriate arguments to select the desired constructor.
  • The special call to this() must appear as the first statement in your delegating constructor.
  • Making this() call to a constructor from other methods is illegal.
    Overloaded Constructor example:
    public class Person {
      private int age;
      private String name;
      
    // this constructor is overloaded
      public Person(int age) {
        this(age,"Nobody"); // delegating to another constructor
      }
    // this constructor is overloaded
      public Person(int age, String name) {
        this.age = age;
        this.name = name;
      }
    
      public int getAge() {
        return age;
      }
    
      public void setAge(int age) {
        this.age = age;
      }
    
      public String getName() {
        return name;
      }
    
      public void setName(String name) {
        this.name = name;
      }
       public static void main(String args[]) {
         // using constructor with two parameters
         Person ricard= new Person(23,"Ricard");
         // using constructor with one parameters
         Person nobody= new Person(34);
         System.out.println("First person is called "
                 +ricard.getName()+" and is "
                 +ricard.getAge()+" years");
         System.out.println("Second person is called "
                 +nobody.getName()+" and is "
                 +nobody.getAge()+" years");
       }
    }
    The result of this is:
    First person is called Ricard and is 23 years
    Second person is called Nobody and is 34 years
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.