Java Constructors

Constructors in Java with Programming Example

In this chapter you will learn:Java Constructors

  1. What is a constructor in java?
  2. What is the need of constructors?
  3. Programming Example
 What is Constructors?

A Constructor is a special method in java which is used for initializing objects. A constructor is a way to pass value to class which is required when objects is initialized. Let’s learn it with this example.

We have a class for temperature converter which converts Fahrenheit into Celsius. The condition is you need Fahrenheit value when class is initialized into object. There is no way to pass value later. A constructor is used here for this purpose.

Every class has one or more than one constructors with same name of class. If you don’t define any constructor, compiler will automatically make default constructor with no value.

How to create Constructor?

A constructor in java can be created same name with class. For example

 class PrintData
 {
  //Default Constructor
  public PrintData()
  {
  }
  //A Constructor which require string argument while initialing objects.
  public PrintData(String name)
  {
  }
 } 


 Programming Example
class DemoCons
{
  public static void main(String[] args)
  {
    Demo dc=new Demo(); //Default Constructor Called
    Demo dc1=new Demo("Hello Friend"); //string constructor called
    dc.PrintMessage(); //PrintMessage() Method Executed
  }
}

class Demo
{
   //Constructor Block
  public Demo()
  {
    System.out.println("I am Default Constructors");
  }
  public Demo(String message)
  {
    System.out.println(message);
  }
  //End of Constructor Block
  
  public void PrintMessage()
  {
    System.out.println("PrintMessage() Method Executed...");
  } 
}

Output

D:\JavaProgram>javac DemoCons.java

D:\JavaProgram>java DemoCons
I am Default Constructors
Hello Friend
PrintMessage() Method Executed…

D:\JavaProgram>__

Explanation:

In the above programming example we have done the following job.

  1. In the above example we have created 2 constructors.
  2. public Demo() is a default constructors. It will executed if object is initialized without parameter.
  3. public Demo(String message): It is second constructor and will be executed when object is initialized with String parameter.
  4. This constructors are executed when objects is initialized as follow:
      Demo dc=new Demo(); //Default Constructor Called
      Demo dc1=new Demo("Hello Friend"); //string constructor called
    
    
    

Summary

In this chapter you have learned how to create and initialized constructors in java. The next chapter will demonstrate Array in Java.


Leave a Reply

Your email address will not be published. Required fields are marked *