Method Constructor Overloading
Method Constructor Overloading
Method Constructor Overloading
• Method Overloading is a feature that allows a class to have more than one
method having the same name, if their argument lists are different.
class DisplayOverloading
{ Output:
public void disp(char c) a
a 10
{
System.out.println(c); In the above example – method disp() is overloaded
} based on the number of parameters – We have two
public void disp(char c, int num) methods with the name disp but the parameters they
{ have are different. Both are having different number
System.out.println(c + " "+num); of parameters.
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading(); obj.disp('a');
obj.disp('a',10);
}
}
Example 2: Overloading – Difference in data type of parameters
In this example, method disp() is overloaded based on the data type of
parameters – We have two methods with the name disp(), one with
parameter of char type and another method with the parameter of int type.
class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)
{
System.out.println(c );
}
}
Output:
a 5
class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
Example3: Overloading – Sequence of data type of arguments
Here method disp() is overloaded based on sequence of data type of parameters – Both the
methods have different sequence of data type in argument list. First method is having argument
list as (char, int) and second is having (int, char). Since the sequence is different, the method can
be overloaded without any issues.
class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3
Output:
I’m the first definition of method disp
{
I’m the second definition of method disp
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
Valid/invalid cases of method overloading
Case 1: Case 4:
int mymethod(int a, int b, float c) float mymethod(int a, float b)
int mymethod(int var1, int var2, float var3) float mymethod(float var1, int var2)
Result: Compile time error. Argument lists are Result: Perfectly fine. Valid case of overloading. Sequence of
exactly same. Both methods are having same the data types of parameters are different, first method is
number, data types and same sequence of having (int, float) and second is having (float, int).
data types.
Case 5:
int mymethod(int a, int b)
Case 2: float mymethod(int var1, int var2)
int mymethod(int a, int b)
int mymethod(float var1, float var2) Result: Compile time error. Argument lists are exactly same.
Even though return type of methods are different, it is not a
Result: Perfectly fine. Valid case of overloading. valid case. Since return type of method doesn’t matter while
Here data types of arguments are different. overloading a method.
Case 3:
int mymethod(int a, int b)
int mymethod(int num)
class Sample5
{
public static void main(String args[])
{
Demo2 obj2= new Demo2();
obj2.myMethod(10,10);
obj2.myMethod(20,12);
}
}
• Answer:
It will throw a compilation error: More than
one method with same name and argument
list cannot be given in a class even though
their return type is different. Method return
type doesn’t matter in case of overloading.
Difference between constructor and method in Java
JAVA CONSTRUCTOR JAVA METHOD
A CONSTRUCTOR MUST NOT HAVE A RETURN A METHOD MUST HAVE A RETURN TYPE.
TYPE.
THE JAVA COMPILER PROVIDES A DEFAULT THE METHOD IS NOT PROVIDED BY THE
CONSTRUCTOR IF YOU DON'T HAVE ANY COMPILER IN ANY CASE.
CONSTRUCTOR IN A CLASS.
THE CONSTRUCTOR NAME MUST BE SAME AS THE METHOD NAME MAY OR MAY NOT BE SAME
THE CLASS NAME. AS CLASS NAME.
Constructor
• Constructor is a special method that gets invoked
“automatically” at the time of object creation.
• Constructor is normally used for initializing objects with default
values unless different values are supplied.
• Constructor has the same name as the class name.
• Constructor cannot return values.
• A class can have more than one constructor as long as they have
different signature (i.e., different input arguments syntax).
Constructor
• Constructor is a block of code that initializes
the newly created object.
• A constructor resembles an instance method
in java but it’s not a method as it doesn’t have
a return type.
• In short constructor and method are different
• How does a constructor work
• To understand the working of constructor, lets take an
example. lets say we have a class MyClass.
Hello()
{
this.name = “constructor example";
}
public static void main(String[] args)
{
Hello obj = new Hello();
System.out.println(obj.name);
}
}
Output:
constructor example
----------
Here we have created an object obj of class Hello and then we displayed the instance variable name
of the object. As you can see that the output is constructor example which is what we have
passed to the name during initialization in constructor.
This shows that when we created the object obj the constructor got invoked.
In this example we have used this keyword, which refers to the current object, object obj in this
• Types of Constructors
• There are three types of constructors: Default,
No-arg constructor and Parameterized.
Default constructor
If you do not implement any constructor in your class, Java compiler inserts a default
constructorinto your code on your behalf. This constructor is known as default
constructor. You would not find it in your source code(the java file) as it would be
inserted into the code during compilation and exists in .class file. This process is shown
in the diagram below:
no-arg constructor:
Constructor with no arguments is known as no-arg constructor. The signature
is same as default constructor, however body can have any code unlike
default constructor where the body of the constructor is empty.
Output:
publicThis is a no
Demo() { }argument constructor
in your class Demo it cannot be called default constructor since you have
written the code of it.
Parameterized constructor
Constructor with arguments(or you can say parameters) is known as
Parameterized constructor.
Example: parameterized constructor
In this example we have a parameterized constructor with two
parameters id and name. While creating the objects obj1 and obj2 I have passed two
arguments so that this constructor gets invoked after creation of obj1 and obj2.
PUBLIC CLASS EMPLOYEE {
INT EMPID;
STRING EMPNAME;
CLASS STUDENT6{
INT ID;
STRING NAME;
//CONSTRUCTOR TO INITIALIZE INTEGER AND STRING
STUDENT6(INT I,STRING N){
ID = I;
NAME = N;
}
//CONSTRUCTOR TO INITIALIZE ANOTHER OBJECT
STUDENT6(STUDENT6 S){
ID = S.ID;
NAME =S.NAME;
}
VOID DISPLAY(){SYSTEM.OUT.PRINTLN(ID+" "+NAME);}
OUTPUT:
111 KARAN
111 KARAN
class JavaExample
{
String web;
JavaExample(String w)
{ public static void main(String args[])
web = w; {
JavaExample obj1 = new
}
JavaExample("BeginnersBook");
/* This is the Copy Constructor, it
* copies the values of one object /* Passing the object as an argument to the
constructor
* to the another object (the object
* This will invoke the copy constructor */
* that invokes this constructor)*/
JavaExample(JavaExample je)
{ JavaExample obj2 = new JavaExample(obj1);
obj1.disp();
web = je.web; obj2.disp();
}
void disp() }
}
{
System.out.println("Website: "+web);
} Output:
Website: BeginnersBook
Website: BeginnersBook
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
Super()
Whenever a child class constructor gets invoked it implicitly invokes the constructor of parent class. You can also say that the
compiler inserts a super(); statement at the beginning of child class constructor.
class MyParentClass
{
MyParentClass()
{
System.out.println("MyParentClass Constructor");
}
}
class MyChildClass extends MyParentClass
{
MyChildClass()
{
System.out.println("MyChildClass Constructor");
}
public static void main(String args[])
{
new MyChildClass();
}
}
Output:
• Quick Recap
• Every class has a constructor whether it’s a normal class or a abstract class.
• Constructors are not methods and they don’t have any return type.
• Constructor name should match with class name .
• Constructor can use any access specifier, they can be declared as private also. Private
constructors are possible in java but there scope is within the class only.
• Like constructors method can also have name same as class name, but still they have
return type, though which we can identify them that they are methods not
constructors.
• If you don’t implement any constructor within the class, compiler will do it for.
• this() and super() should be the first statement in the constructor code. If you don’t
mention them, compiler does it for you accordingly.
• Constructor overloading is possible but overriding is not possible. Which means we can
have overloaded constructor in our class but we can’t override a constructor.
• Constructors can not be inherited.
• If Super class doesn’t have a no-arg(default) constructor then compiler would not insert
a default constructor in child class as it does in normal scenario.
• Interfaces do not have constructors.
• Abstract class can have constructor and it gets invoked when a class, which implements
interface, is instantiated. (i.e. object creation of concrete class).
• A constructor can also invoke another constructor of the same class – By using this(). If
you want to invoke a parameterized constructor then do it like this: this(parameter list).