In this chapter you will learn:
- What is a constructor in java?
- What is the need of constructors?
- Programming Example
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) { } }
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.
- In the above example we have created 2 constructors.
public Demo()
is a default constructors. It will executed if object is initialized without parameter.public Demo(String message)
: It is second constructor and will be executed when object is initialized with String parameter.- 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.