Constructor overloading in Java

Java Programming Java8Object Oriented Programming

Yes! Java supports constructor overloading. In constructor loading, we create multiple constructors with the same name but with different parameters types or with different no of parameters.

Example

Live Demo

public class Tester {
 
   private String message;
 
   public Tester(){
      message = "Hello World!";
   }
   public Tester(String message){
      this.message = message;
   }
 
   public String getMessage(){
      return message ;
   }
 
   public void setMessage(String message){
      this.message = message;
   }
 
   public static void main(String[] args) {
      Tester tester = new Tester();
      System.out.println(tester.getMessage());
   
      Tester tester1 = new Tester("Welcome");
      System.out.println(tester1.getMessage());  
   }
}   

Output

Hello World!
Welcome


raja
Published on 22-Apr-2018 23:41:01
Advertisements