Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Method Constructor Overloading

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 30

Method 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.

• It is similar to constructor overloading in Java, that allows a class to have


more than one constructor having different argument lists.

• Argument list it means the parameters that a method has:


• For example
The argument list of a method add(int a, int b) having two parameters is
different from the argument list of the
method add(int a, int b, int c) having three parameters.

Method overloading is an example of Static Polymorphism.


1. Static Polymorphism is also known as compile time binding or early
binding.
2. Static binding happens at compile time. Method overloading is an
example of static binding where binding of method call to its definition
happens at Compile time.
Three ways to overload a method
• In order to overload a method, the argument lists of the methods must differ in
either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
• 2. Data type of parameters.
For example:
add(int, int)
add(int, float)
• 3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
• Invalid case of method overloading:
If two methods have same name, same parameters and have different return type,
then this is not a valid method overloading example. This will throw compilation
error.
• int add(int, int)
Example method overloading

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)

Result: Perfectly fine. Valid case of overloading.


Here number of arguments are different.
Guess the answers
CLASS DEMO
{
PUBLIC INT MYMETHOD(INT NUM1, INT NUM2)
{
SYSTEM.OUT.PRINTLN("FIRST MYMETHOD OF CLASS DEMO");
RETURN NUM1+NUM2;
}
PUBLIC INT MYMETHOD(INT VAR1, INT VAR2)
{
SYSTEM.OUT.PRINTLN("SECOND MYMETHOD OF CLASS DEMO");
RETURN VAR1-VAR2;
}
}
CLASS SAMPLE4
{
PUBLIC STATIC VOID MAIN(STRING ARGS[])
{
DEMO OBJ1= NEW DEMO();
OBJ1.MYMETHOD(10,10);
OBJ1.MYMETHOD(20,12);
}
}
• Answer:
It will throw a compilation error: More than
one method with same name and argument
list cannot be defined in a same class.
class Demo2
{
public double myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo"); return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}

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 IS USED TO INITIALIZE THE A METHOD IS USED TO EXPOSE THE BEHAVIOR


STATE OF AN OBJECT. OF AN OBJECT.

A CONSTRUCTOR MUST NOT HAVE A RETURN A METHOD MUST HAVE A RETURN TYPE.
TYPE.

THE CONSTRUCTOR IS INVOKED IMPLICITLY. THE METHOD IS INVOKED EXPLICITLY.

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.

public class MyClass


{
//This is the constructor MyClass()
{
}
.. }

• When we create the object of MyClass like this:


• MyClass obj = new MyClass()

• The new keyword here creates the object of


class MyClass and invokes the constructor to initialize this
newly created object.
• A simple constructor program
public class Hello
{
String name; //Constructor

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.

Example: no-arg constructor


class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[])
{
new Demo();
}
}

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;

//PARAMETERIZED CONSTRUCTOR WITH TWO PARAMETERS


EMPLOYEE(INT ID, STRING NAME){
THIS.EMPID = ID;
THIS.EMPNAME = NAME;
}
VOID INFO(){
SYSTEM.OUT.PRINTLN("ID: "+EMPID+" NAME: "+EMPNAME);
}

PUBLIC STATIC VOID MAIN(STRING ARGS[]){


EMPLOYEE OBJ1 = NEW EMPLOYEE(10245,"CHAITANYA");
EMPLOYEE OBJ2 = NEW EMPLOYEE(92232,"NEGAN");
OBJ1.INFO();
OBJ2.INFO();
}
}
OUTPUT:
ID: 10245 NAME: CHAITANYA
ID: 92232 NAME: NEGAN
class Example2
{
private int var;
//default constructor
Example2: parameterized
public Example2() constructor
{ In this example, we have two
this.var = 10; constructors, a default
} constructor and a parameterized
//parameterized constructor
constructor. When we do not pass
public Example2(int num)
{
any parameter while creating the
this.var = num; object using new keyword then
} default constructor is invoked,
public int getValue() however when you pass a
{ parameter then parameterized
return var;
constructor that matches with the
}
public static void main(String args[])
passed parameters list gets
{ invoked.
Example2 obj = new Example2();
Example2 obj2 = new Example2(100);
System.out.println("var is: "+obj.getValue());
Output:
System.out.println("var is: "+obj2.getValue());
} var is: 10
} var is: 100
What if you implement only parameterized constructor in class
class Example3
{
Output: It will throw a compilation error. The
private int var; reason is, the statement Example3 myobj = new Example3() is
public Example3(int num) invoking a default constructor which we don’t have
in our program. when you don’t implement any
{ constructor in your class, compiler inserts the default
constructor into your code, however when you
var=num;
implement any constructor (in above example I have
} implemented parameterized constructor with int
parameter), then you don’t receive the default
public int getValue() constructor by compiler into your code.
{ If we remove the parameterized constructor from the
above code then the program would run fine,
return var; because then compiler would insert the default
} constructor into your code.

public static void main(String args[])


{
Example3 myobj = new Example3();
System.out.println("value of var is: "+myobj.getValue());
}
Constructor Overloading
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.
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25
Copy Constructor

A copy constructor is used for copying the values
of one object to another object.

• There are many ways to copy the values of one


object into another in java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
//JAVA PROGRAM TO INITIALIZE THE VALUES FROM ONE OBJECT TO ANOTHER

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);}

PUBLIC STATIC VOID MAIN(STRING ARGS[]){


STUDENT6 S1 = NEW STUDENT6(111,"KARAN");
STUDENT6 S2 = NEW STUDENT6(S1);
S1.DISPLAY();
S2.DISPLAY();
}
}

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);}

public static void main(String args[]){


Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
Output:
s2.display();
111 Karan
}
111 Karan
}
Assignment on constructor
• Create a class date with day,month,year as members. Write
appropriate member function. Create another class student, which has
id, name, date of birth and marks of 3 subjects as members. Write
appropriate constructor for -the student which assigns values to the
members. Accept the details as command line argument and create a
student object using the argument. Display the student details in a
proper format.

• Define a class Employee having private members-id, name,


department,salary. Define default and parameterized constructors.
Create a subclass called “Manager” with private member bonus.
Define methods accept and display in both the classes. Create n
objects of the Manager class and display the details of the manager
having maximum total salary(salary+bonus)
Constructor Chaining
When A constructor calls another constructor of same class then this is called constructor chaining.

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).

You might also like