Java-Constructors-Constructor Overloading-examples.How constructors are different from methods in Java?

Conctructors

Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements that are executed at time of Object creation.

Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.
Constructor has same name as the class and looks like this in a java code.


public class KnowledgefactoryThrowsDemo {
// This is the deafult constructor
public KnowledgefactoryThrowsDemo() {
// TODO
}
// TODO
}

Note that the constructor name matches with the class name and it doesn’t have a return type.


Rules for writing Constructor:


  • Constructor(s) of a class must has same name as the class name in which it resides.
  • A constructor in Java can not be abstract, final, static and Synchronized.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

Types of constructor

No-argument constructor
A constructor that has no parameter is known as default constructor. If we don’t define a constructor in a class, then compiler creates default constructor(with no arguments) for the class. And if we write a constructor with arguments or no-arguments then the compiler does not create a default constructor.
Default constructor provides the default values to the object like 0, null, etc. depending on the type.

Example(No-argument constructor):

public class KnowledgefactoryThrowsDemo {

// this would be invoked while an object
// of that class is created.
KnowledgefactoryThrowsDemo() {
System.out.println("Constructor called");
}

// TODO
public static void main(String[] args) {
KnowledgefactoryThrowsDemo obj = new                                                                          KnowledgefactoryThrowsDemo();
}
}

Output:Constructor called


Example(Default Constructor)

public class KnowledgefactoryThrowsDemo {

/*

* If you do not create constructors yourself, the Java compiler will
* automatically create a no-argument constructor during run- time.This
* constructor is known as default constructor.The default constructor
* initializes any uninitialized instance variables.
*/

void helloWorld() {

System.out.println(" hellow world method called");
}

// TODO

public static void main(String[] args) {
// invoking default constructor
KnowledgefactoryThrowsDemo obj = new KnowledgefactoryThrowsDemo();
obj.helloWorld();
}
}

Output: hellow world method called




Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with your own values, then use a parameterized constructor.

Example:
public class KnowledgefactoryThrowsDemo {
// data members of the class.
String name;
int age;

// constructor would initialize data members
// with the values of passed arguments while
// object of that class created.
KnowledgefactoryThrowsDemo(int age, String name) {
this.age = age;
this.name = name;
}

// TODO
public static void main(String[] args) {
// invoking parameterized constructor
KnowledgefactoryThrowsDemo obj = new                                                                           KnowledgefactoryThrowsDemo(50, "sibin");
System.out.println("Age: " + obj.age + "  Name: " + obj.name);
}
}

Output: Age: 50  Name: sibin



Constructor Overloading

Like methods, constructors can also be overloaded.Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.
For example ArrayList has three types of constructor
ArrayList(): This constructor is used to build an empty array list
ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from collection c
ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified


Example:

public class KnowledgefactoryThrowsDemo {

// constructor with one argument
KnowledgefactoryThrowsDemo(String name) {
System.out.println("Constructor with one " + "argument - String : " + name);
}

// constructor with two arguments
KnowledgefactoryThrowsDemo(String name, int age) {
System.out.println("Constructor with two arguments : " + " String and Integer : " + name + " " + age);
}

// TODO
public static void main(String[] args) {
// Invoke the constructor with one argument of
// type 'String'.
KnowledgefactoryThrowsDemo obj1 = new KnowledgefactoryThrowsDemo("sibin");
// Invoke the constructor with two arguments
KnowledgefactoryThrowsDemo obj2 = new       KnowledgefactoryThrowsDemo("sibin", 51);
}
}

Output:
            Constructor with one argument - String : sibin
            Constructor with two arguments :  String and Integer : sibin 51


How constructors are different from methods in Java?

Constructor(s) must have the same name as the class within which it defined while it is not necessary for the method in java.
Constructor(s) do not return any type while method(s) have the return type or void if does not return any value.
Constructor is called only once at the time of Object creation while method(s) can be called any numbers of time.


This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Comments

  1. Genuine and Free jobs!
    Don't miss any job opportunities!
    Improve your life, only one step!

    More Java jobs info, Please join the Java Jobs group:
    https://chat.whatsapp.com/HLFm93tkHQR4zu8hafpqSl

    ReplyDelete

Post a Comment