5. Method Overloading, Constructors
Srinivas Prasad K T
Engineering Manager @ Decathlon Technology || Ex Harman || Ex E2Open || Oracle Java? || Spring Boot? || WDIO? || Playwright? || Java Script & Type Script? || Scrum? || Gatling? || AI? || Tricentis Tosca? || ACCELQ?
Recursion
What is Java recursion?
So why use Java Recursion?
class Recursion
{
int fact(int n)
{
int result;
if (n==1) return 1;
result = fact (n-1) * n;
return result;
}
public static void main (String args[])
{
System.out.println("Program starts...");
Recursion f =new Recursion();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
System.out.println("Program Ends...");
}
}
Output:
Program starts...
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Program Ends...
Call by Value and Call by Reference
Ex:
class CallByValue
{
public static void main ( String[] args )
{
System.out.println("Program starts...");
int x =3;
System.out.println ( "Value of x before calling increment() is "+x);
increment(x);
System.out.println ( "Value of x after calling increment() is "+x);
System.out.println("Program ends...");
}
public static void increment ( int a )
{
System.out.println ( "Value of a before incrementing is "+a);
a= a+1;
System.out.println ( "Value of a after incrementing is "+a);
}
}
Output:
Program starts...
Value of x before calling increment() is 3
Value of a before incrementing is 3
Value of a after incrementing is 4
Value of x after calling increment() is 3
Program ends...
class CallByReference
{
int x;
public static void main ( String[] args )
{
System.out.println("Program starts...");
CallByReference a = new CallByReference();
a.x=3;
System.out.println("Value of X before calling increment() is "+a.x);
increment(a);
System.out.println("Value of X after calling increment() is "+a.x);
System.out.println("Program ends...");
}
public static void increment(CallByReference n)
{
System.out.println("Value of X before incrementing x is "+n.x);
n.x=n.x+1;
System.out.println("Value of X after incrementing x is "+n.x);
}
}
Output:
Program starts...
Value of a.x before calling increment() is 3
Value of n.x before incrementing x is 3
Value of n.x after incrementing x is 4
Value of a.x after calling increment() is 4
Program ends...
Method Overloading
When we go for method overloading??
Advantage of method overloading?
Ex:?
class Am
{
public void max(int x, double y)
{
System.out.println("Running Max of int x and double y ");
}
public void max(double x, int y)
{
System.out.println("Running Max method of Double x and int y method ");
}
}
public class Maxs
{
public static void main(String[] args)
{
Am a = new Am();
a.max(2, 2.0);
a.max(5.6, 5);
//a.max(2, 6);
}
}
Output:
Program Starts...
Maximum number is: 6
Maximum number is: 5.0
Maximum number is: 10.0
Program Ends...
public class Math
{
public static int Max(int x, int y)
{
int max;
if(x>y)
max=x;
else
max=y;
return max;
}
public static double Max(double x, double y)
{
double max;
if(x>y)
max=x;
else
max=y;
return max;
}
public static void main(String[] args)
{
System.out.println("Program Starts...");
System.out.println("Maximum number is: "+Math.Max(5, 6));
System.out.println("Maximum number is: "+Math.Max(5.0, 4.0));
System.out.println("Maximum number is: "+Math.Max(10, 9.0));
System.out.println("Program Ends...");
}
}
Output:
Program Starts...
Maximum number is: 6
Maximum number is: 5.0
Maximum number is: 10.0
Program Ends...
public class Sample
{
public void test()
{
System.out.println("Running test() method: ");
}
public void test(int i)
{
System.out.println("Running test(int) method: ");
}
public void test(double d)
{
System.out.println("Running test(double) method: ");
}
public void test(int i, double d)
{
System.out.println("Running test(int,double) method: ");
}
public static void main(String[] args)
{
System.out.println("Program starts...");
Sample s = new Sample();
s.test();
s.test(5);
s.test(10.23);
s.test(5,10.23);
}
}
Program starts...
Running test() method:?
Running test(int) method:?
Running test(double) method:?
Running test(int,double) method:?
Program ends...
Method Overloading by changing the no. of arguments
class Calculation
{
void sum(int a,int b)
{
System.out.println("The addition of two numbers is: "+(a+b));
}
void sum(int a,int b,int c)
{
System.out.println("The addition of three numbers is:"+(a+b+c));
}
public static void main(String args[])
{
System.out.println("Program Starts...");
Calculation c =new Calculation();
c.sum(12,12);
c.sum(20,20,20);
System.out.println("Program ends...");
}
}
Output:
Program Starts...
The addition of two numbers is: 24
The addition of three numbers is:60
Program ends...
Method Overloading by changing data type of argument
class Calculation1
{
void sum(int a,int b)
{
System.out.println("Sum of two integer values is: "+(a+b));
}
void sum(double a,double b)
{
System.out.println("Sum of two decimal values is: "+(a+b));
}
public static void main(String args[])
{
System.out.println("Program starts...");
Calculation1 obj=new Calculation1();
obj.sum(10.5,10.5);
obj.sum(20,20);
System.out.println("Program ends...");
}
}
Output:
Program starts...
Sum of two decimal values is: 21.0
Sum of two integer values is: 40
Program ends...
Why Method Overloading is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur:
class Calculation3
{
int sum(int a,int b)
{
System.out.println(a+b);
}
double sum(int a,int b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Calculation3 obj=new Calculation3();
int result=obj.sum(20,20); //Compile Time Error
}
}
Output: Compile time error
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
class OverloadingCalculation
{
void sum(int a,long b)
{
System.out.println("Sum of int and long values: "+(a+b));
}
void sum(int a,int b,int c)
{
System.out.println("Sum of int int and int values: "+(a+b+c));
}
public static void main(String args[])
{
System.out.println("Program starts...");
OverloadingCalculation obj=new OverloadingCalculation();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
System.out.println("Program ends...");
}
}
Output:
Program starts...
Sum of int and long values: 40
Sum of int int and int values: 60
Program ends...
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingCalculation1
{
void sum(int a,int b)
{
System.out.println("int arg method invoked");
}
void sum(long a,long b)
{
System.out.println("long arg method invoked");
}
public static void main(String args[])
{
System.out.println("Program starts...");
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now int arg sum() method gets invoked
System.out.println("Program ends...");
}
}
Output:
Program starts...
int arg method invoked
Program ends...
If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.
class OverloadingCalculation1
{
void sum(int a,long b)
{
System.out.println("a method invoked");
}
void sum(long a,int b)
{
System.out.println("b method invoked");
}
public static void main(String args[])
{
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now ambiguity
}
}
Output:
Output: Compile Time Error
Constructor?
class car
{
String carColor = "White";
//Contains default constructors
}
public class DefaultConstructor
{
public static void main(String[] args)
{
System.out.println("Program starts...");
car c = new car();//Creating an instance of class car
System.out.println("Car color is: "+c.carColor);
System.out.println("Program ends...");
}
}
Output:
???????Program starts...
Car color is: White
Program ends...
Syntax:
Modifier Constructor Name (args)
{
? ----------
? ----------?
}?
class cars
{
String color;
cars()
{
System.out.println("Running car constructor: ");
color = "White";
}
}
public class DemoConstructor
{
public static void main(String[] args)
{
System.out.println("Program Starts...");
cars c1 = new cars();
System.out.println("Car color is: "+c1.color);
System.out.println("--------------------------");
cars c2 = new cars();
c2.color = "Blue";
System.out.println("Car color is: "+c2.color);
System.out.println("Program ends...");
}
}
Output:
Program Starts...
Running car constructor:?
Car color is: White
--------------------------
Running car constructor:?
Car color is: Blue
Program ends...
Why constructor does not return?
Types of java constructors
There are two types of constructors:
Java Default Constructor
A constructor that has no parameter is known as default constructor.
Syntax of default constructor:
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
What is the purpose of default constructor?
Default constructor provides the default values to the object like 0, null etc. depending on the type.
Example of default constructor that displays the default values
class car
{
String carColor = "White";
}
public class DefaultConstructor
{
public static void main(String[] args)
{
System.out.println("Program starts...");
car c = new car();
System.out.println("Car color is: "+c.carColor);
System.out.println("Program ends...");
}
}
Output:
Program starts...
Car color is: White
Program ends...
Explanation: In the above class, you are not creating any constructor so compiler provides you a default constructor.?
Java parameterized constructor
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
class Car1
{
String color;
Car1(String Shade)
{
System.out.println("Running car constructor: ");
color = Shade;
}
}
public class ArgumentConstructor
{
public static void main(String[] args)
{
System.out.println("Program starts...");
Car1 c = new Car1("Blue");
System.out.println("The color of car is : "+c.color);
Car1 d = new Car1("Yellow");
System.out.println("The color of car is: "+d.color);
System.out.println("Program ends...");
}
}
Output:
Program starts...
Running car constructor:?
The color of car is : Blue
Running car constructor:?
The color of car is: Yellow
Program ends...
Constructor Overloading in Java
Programs:
class student
{
int stId;
double stMarks;
student(int a)
{
System.out.println("Running student(int) constructor");
stId = a;
}
student(double b)
{
System.out.println("Running student(double) constructor");
stMarks = b;
}
student(int a, double b)
{
System.out.println("Running student(int, double) constructor");
stId = a;
stMarks = b;
}
void displayDetails()
{
System.out.println("Student ID: "+stId);
System.out.println("Student Marks: "+stMarks);
}
}
public class ConstructorOverloading
{
public static void main(String[] args)
{
System.out.println("Program starts...");
student st1 = new student(101);
st1.displayDetails();
System.out.println("-----------------");
student st2 = new student(62.23);
st2.displayDetails();
System.out.println("------------------");
student st3 = new student(101, 62.23);
st3.displayDetails();
System.out.println("Program ends...");
}
}
Output:
Program starts...
Running student(int) constructor
Student ID: 101
Student Marks: 0.0
-----------------
Running student(double) constructor
Student ID: 0
Student Marks: 62.23
------------------
Running student(int, double) constructor
Student ID: 101
Student Marks: 62.23
Program ends...
class Student
{
int id;
String name;
int age;
Student(int i, String n)
{
id = i;
name = n;
}
Student(int i, String n, int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println("Student ID: "+id);
System.out.println("Student Name: "+name);
System.out.println("Student Age: "+age);
}
public static void main(String args[])
{
System.out.println("Program starts...");
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
System.out.println("-------------------");
s2.display();
System.out.println("Program ends...");
}
}
Output:
Program starts...
Student ID: 111
Student Name: Karan
Student Age: 0
-------------------
Student ID: 222
Student Name: Aryan
Student Age: 25
Program ends...
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
In this example, we are going to copy the values of one object into another using java constructor.
class CopyConstructor
{
int id;
String name;
CopyConstructor(int i, String n)
{
id = i;
name = n;
}
CopyConstructor(CopyConstructor s)
{
id = s.id;
name =s.name;
}
public void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
System.out.println("Program starts...");
CopyConstructor s1 = new CopyConstructor(111,"Karan");
CopyConstructor s2 = new CopyConstructor(s1);
s2.display();
System.out.println("Program ends...");
}
}
Output:
Program starts...
111 Karan
Program ends...
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[])
{
System.out.println("Program starts...");
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
System.out.println("Program ends...");
}
}
Output:
Program starts...
111 Karan
Program ends...
Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method.
Advantages
Note:?
This calling statement/call to this statement
//Program to call multiple constructor using single instance using this() statments
class Sample1
{
Sample1()
{
System.out.println("Running sample1() constructor");
}
Sample1(int a)
{
this();
System.out.println("Running sample1(int) constructor");
}
Sample1(double d)
{
this(5);
System.out.println("Running sample1(double) constructor");
}
}
public class ThisStatements
{
public static void main(String args[])
{
System.out.println("Program starts...");
Sample1 s = new Sample1(12.23);
System.out.println("Program ends...");
}
}
Output:
Program starts...
Running sample1() constructor
Running sample1(int) constructor
Running sample1(double) constructor
Program ends...
???
This keyword
Types of parameters
There are two types of parameters?
Implicit parameter:
Ex: MyData
Ex:?
?class MyData
{
String MyName;
public void DisplayName()
{
System.out.println(MyName);
}
}
public class Main
{
public static void main(String[] args)
{
System.out.println("Program starts...");
MyData m = new MyData();
m.DisplayName(); //Implicit calling
System.out.println("Program ends...");
}
}
Explicit parameters:
Any parameter supplied to the method within its brackets becomes explicit parameter.
Ex:?
class MyData
{
public void DisplayName(String MyName)
{
System.out.println(MyName);
}
}
public class Main
{
public static void main(String[] args)
{
System.out.println("Program starts...");
MyData m = new MyData();
m.DisplayName("Java");
System.out.println("Program ends...");
}
}
This Keyword
Use of this keyword
Note: One point to remember is that this is associated with the instance of the class, so it will not work in static methods
Variables use in inside the class and outside the class
Inside the class example:?
class A1
{
int i =10;
public void Display()
{
// In inside the class we can directly use the variables.
System.out.println(i);
}
}
Outside the class example:?
class A1
{
int i =10;
}
public class InsideOutSide
{
public static void main(String[] args)
{
A1 a = new A1();
System.out.println(a.i);
// To use the variable in outside the class we have to create the object first than
// by using the object reference we will use the variable.
}
}
We can see the difference in using the variable in inside the class and outside the class, to use in inside the class we will directly use the variables where as in outside the class we always create the object first than we will use the variables.?
class A1
{
int i =10;
public void Display()
{
System.out.println("i:"+i);
}
}
public class InsideOutSide
{
public static void main(String[] args)
{
System.out.println("Program stats..");
A1 a1 = new A1();
a1.Display();
A1 a2 = new A1();
a2.Display();
System.out.println("Program ends...");
}
}
Than what to do, to use the variable inside the class,
If we see the above example, when we create the objects and call the particular object that particular objects data members or methods will be called and it will be executed.
This is where we use the keyword ‘this’
class A1
{
int i =10;
public void Display()
{
System.out.println("i:"+this.i);
}
}
public class InsideOutSide
{
public static void main(String[] args)
{
System.out.println("Program stats..");
A1 a1 = new A1();
a1.Display();
A1 a2 = new A1();
a2.Display();
System.out.println("Program ends...");
}
}
When we create the and execute the object, ‘this’ keyword will become that object?
i.e. ‘this’ keyword will be equal to the object which is executing at the time, nothing but ‘this’ keyword will hold the address of current object of class.
Then why do we need ‘this’ keyword, instead we can directly refer the data members and methods on reference variable, Coz,?
????When a local variable has the same name as an instance variable or global variable, the local variable hides the instance variable.
class A1
{
int i =10;
public void Display()
{
int i = 20;
System.out.println("i:"+i);
}
}
class A1
{
int i =10;
public void Display()
{
int i = 20;
System.out.println("i:"+i);
System.out.println("i:"+this.i);
}
}
public class ThisKeyword
{
public static void main(String[] args)
{
System.out.println("Program starts...");
SomeClass s = new SomeClass();
System.out.println("Reference object: "+s);
s.display();
System.out.println("Program ends...");
}
}
class SomeClass
{
int no = 10;
public void display()
{
int no = 20;
System.out.println(no);
System.out.println("this object: "+this);
}
}
Output:?
Program starts...
Reference object: com.constructor.SomeClass@7e938b4a
20
this object: com.constructor.SomeClass@7e938b4a
Program ends...
If you observe the output of the above program the address of reference variable and the ‘this’ keyword will be the same,? i.e. coz the ‘this’ keyword will be holding the address of current executing object address always.
Will take an another example,?
public class ThisKeyword
{
public static void main(String[] args)
{
System.out.println("Program starts...");
SomeClass s = new SomeClass();
System.out.println("Reference object s: "+s);
s.display();
SomeClass s1 = new SomeClass();
System.out.println("Reference object s1 : "+s1);
s1.display();
System.out.println("Program ends...");
}
}
class SomeClass
{
int no = 10;
public void display()
{
int no = 20;
System.out.println(no);
System.out.println("this object: "+this);
}
}
Output:?
Program starts...
Reference object s: com.constructor.SomeClass@89de832
20
this object: com.constructor.SomeClass@89de832
Reference object s1 : com.constructor.SomeClass@36f72f09
20
this object: com.constructor.SomeClass@36f72f09
Program ends...
Will look into the exact example for using the ‘this’ keyword.
public class ThisKeyword
{
public static void main(String[] args)
{
System.out.println("Program starts...");
SomeClass s = new SomeClass();
s.display();
SomeClass s1 = new SomeClass();
s1.display();
System.out.println("Program ends...");
}
}
class SomeClass
{
int no = 10;
public void display()
{
int no = 20;
System.out.println(no);
System.out.println("instance variable: "+this.no);
}
}
Output:
Program starts...
Running sample() constructor:?
StudentId: 10
StudentMarks: 12.24
Running sample() constructor:?
StudentId: 11
StudentMarks: 12.25
Program ends...
class sample
{
int stId;
double stMarks;
sample(int Id, double Marks)
{
System.out.println("Running sample() constructor: ");
this.stId = Id;
this.stMarks = Marks;
}
}
public class ThisKeyword1
{
public static void main(String[] args)
{
System.out.println("Program starts...");
sample st = new sample(10, 12.24);
System.out.println("StudentId: " +st.stId);
System.out.println("StudentMarks: "+st.stMarks);
sample st1 = new sample(11, 12.25);
System.out.println("StudentId: " +st1.stId);
System.out.println("StudentMarks: "+st1.stMarks);
System.out.println("Program ends...");
}
}
Output:
Program starts...
First print i = 10
Second print i = 20
Third print i = 300
fourth point i = 420
Fifth print i = 20
Program ends...
public class Demo2
{
int stID;
double stMarks;
Demo2(int stId, double stMarks)
{
System.out.println("Running Demo2() constructor");
this.stID = stId;
this.stMarks = stMarks;
}
public static void main(String[] args)
{
System.out.println("Program starts...");
Demo2 d = new Demo2(1212, 56.21);
System.out.println("Student ID: "+d.stID);
System.out.println("Student Marks: "+d.stMarks);
System.out.println("Program ends...");
}
}
Output:
Program starts...
Running Demo2() constructor
Student ID: 1212
Student Marks: 56.21
Program ends...
class Sample4
{
String name;
Sample4(String Username)
{
this.name = Username;
}
void Display()
{
Sample4 s2 = new Sample4("Suresh");
System.out.println("Name: "+this.name);
//refering current instance member
System.out.println("Name: "+s2.name);
//refering other instance(s2) name
}
}
public class Demo3
{
public static void main(String[] args)
{
System.out.println("Program starts...");
Sample4 s1 = new Sample4("Ramesh");
s1.Display();
System.out.println("Program ends...");
}
}
Output:
Program starts...
Name: Ramesh
Name: Suresh
Program ends...
class Employee
{
double empSalary;
Employee(double empSalary)
{
this.empSalary = empSalary;
}
void compareSalary(Employee emp)
{
if(empSalary == this.empSalary)
{
System.out.println("Employee salary is same");
}
else
{
System.out.println("Employee salary is not same");
}
}
}
public class Demo1
{
public static void main(String[] args)
{
System.out.println("Program starts...");
Employee Suresh = new Employee(24450.45);
Employee Ramesh = new Employee(25450.45);
Employee Mahesh = new Employee(24450.45);
Suresh.compareSalary(Ramesh);
Suresh.compareSalary(Mahesh);
System.out.println("Program ends...");
}
}
Output:
Program starts...
Employee salary is not same
Employee salary is same
Program ends...
Difference between constructor and method in java
There are many differences between constructors and methods. They are given below.
What is invoked firstly instance initializer block or constructor?
class InstanceBlock
{
int speed;
InstanceBlock()
{
System.out.println("constructor is invoked");
}
{
System.out.println("instance initializer block invoked");
}
public static void main(String args[])
{
System.out.println("Program starts...");
InstanceBlock b1=new InstanceBlock();
InstanceBlock b2=new InstanceBlock();
System.out.println("Program ends...");
}
}
Output:
Program starts...
instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
Program ends...
In the above example, it seems that instance initializer block is firstly invoked but NO. Instance initializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the constructor after the first statement super (). So firstly, constructor is invoked. Let's understand it by the figure given below:?
Note: The java compiler copies the code of instance initializer block in every constructor.
Rules for instance initializer block:
There are mainly three rules for the instance initializer block. They are as follows:?
Program of instance initializer block that is invoked after super ()
class A
{
A()
{
System.out.println("parent class constructor invoked");
}
}
class B3 extends A
{
B3()
{
super();
System.out.println("child class constructor invoked");
}
{
System.out.println("instance initializer block is invoked");
}
public static void main(String args[])
{
System.out.println("Program starts...");
B3 b=new B3();
System.out.println("Program ends...");
}
}
Output:
Program starts...
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
Program ends...