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

 Programming Example

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:

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 *