Ch 4 Constructors
What is a Constructor?
• In Java, every class has its constructor that is invoked automatically when
an object of the class is created.
• A constructor has the same name as that of class and it does not return
any value.
class Test {
Test()
{
// constructor body
}
}
Types of Constructors
• Non-Parameterized Constructor(default):
A constructor that accepts no parameter.
• Parameterized Constructor
we can pass parameters to a constructor. Such constructors are known as
a parameterized constructor.
How are constructors invoked?
Constructor function gets called (invoked) automatically whenever an object
is created.
Difference between function and constructor.
Constructor is used to initialize an object whereas method is used to
exhibits functionality of an object.
Constructors are invoked implicitly whereas methods are invoked
explicitly.
Constructor does not return any value where the method may/may not
return a value.
In case constructor is not present, a default constructor is provided by
java compiler. In the case of a method, no default method is provided.
Constructor should be of the same name as that of class. Method name
should not be of the same name as that of class.
Constructor overloading
• Just like method overloading, constructors also can be overloaded.
• Same constructor declared with different parameters in the same class is
known as constructor overloading.
• Compiler differentiates which constructor is to be called depending upon
the number of parameters and their sequence of data types.
Constructor Example
class MyClass
{
MyClass() //non-parameterized constructor
{
System.out.println("Welcome");
}
MyClass(String s) //parameterized constructor
{
System.out.println("Hi," + s);
}
public static void display()
{
System.out.println("Hello, everyone");
}
public static void main (String args[])
{
//object1 is created-> non-parameterised constructor is called
MyClass c1=new MyClass();
//object2 is created-> parameterisd constructor is called
MyClass c2=new MyClass("Asha");
display();// call to display method
}
}