5. Method Overloading, Constructors

5. Method Overloading, Constructors


Recursion

What is Java recursion?

  • ?In computer programming, it’s the process of having a method continually call itself until a defined point of termination.
  • The method will call itself, and it will execute the code inside, which is to call itself, until a defined point of termination.

So why use Java Recursion?

  • There are certain problems that just make sense to solve via Java recursion. This is the case because sometimes when solving problems recursively, you can really cut down on code with your solutions. For example, let’s take a look at something called the Factorial sequence

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

  • Pass by value and pass by reference or call by value and call by reference are two mechanisms to pass parameters to methods in a programming language.?
  • In pass by value mechanism method is passed the value provided by the caller, therefore, changes made to the formal parameters of the method have no effect on the original values that were passed by the caller.?
  • But pass by reference means that the method gets the location of the variable that the caller provides. Thus, changes made to the formal parameters will affect the actual arguments used to call the method.

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

  • In the above output, the value of x has remain unchanged, even though it was passed as a parameter to the increment () method. (This program contains two static methods. The method increment() was also specified to be static since only static members can be accessed by a static method)?
  • And now, we move on to the second program, where we will make use of class Number that contains a single instance variable x.

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

  • Now, there is a remarkable difference between the outputs obtained in the above two programs.
  • ?In the first program, the change made to the variable a inside the increment () method had no effect on the original variable x that was passed as an argument.?
  • On the other hand, in the second program, changes made to the variable x that was a part of the object in the increment () method had an effect on the original variable (the object which contained that integer variable) that was passed as an argument.?
  • The difference lies in the type of the variable that was passed as an argument. int is a primitive data type while Number is a reference data type.?
  • Primitive data types in Java are passed by value while reference data types are passed by reference.?

Method Overloading

  • Developing a method with same name and different signature in a class is known as method overloading.
  • The method overloading should meet any of the following?

  • The argument type should differ
  • The argument length should differ
  • The argument position should differ

  • In a class we can overload both static method and non-static method
  • A subclass can overload super class method
  • While developing an application, the same operation, Which has to be implemented in different way than we develop overloaded method
  • Java distinguishes overloaded methods according to the number of parameters and the types of the parameters
  • When the java code is written to call a method, the compiler checks if the first argument has the? same type as first parameter, the second argument has the same type as the second parameter
  • We can overload void methods, to methods which return a value, to static methods, to non-static methods, and also constructors.

When we go for method overloading??

  • When we doing a same operation but wants to do different way on that time we go for “Method overloading
  • If we have to perform only one operation, having same name of the methods increases the readability of the program

Advantage of method overloading?

  • Method overloading increases the readability of the program.

Ex:?

  1. Suppose we have to perform finding the maximum of two numbers, if we write a method such as a ‘Int max (int a, int b)’, it will find the maximum of two integer values, suppose if we want to find the maximum value of double, will develop a method ‘Double max (double a, double b)’ then it may be difficult to for us as a programmers to understand the behavior of the method because its name differs, so to overcome from this we perform method overloading.

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

  1. Will see one more example, Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a (int, int) for two parameters, and b (int, int, int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. So, we perform method overloading to figure out the program quickly.

Method Overloading by changing the no. of arguments

  • In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.

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

  • In this example, we have created two overloaded methods that differ in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.

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

  • Constructors are a block just like method which gets executed whenever we create an instance of the class.
  • Constructor is special method which has no return type and return value.
  • Every java class should contain at-least one constructor. If we don’t develop constructor, compiler writes a constructor at the time of compilation such constructor created by the compiler is known as “Default constructor”.
  • A programmer can also develop constructor inside a class body.

Syntax:

Modifier Constructor Name (args)

{

? ----------

? ----------?

}?

  • Following values to be followed while defining constructor?
  • The constructor name should be same as class name
  • The constructor should not be defined with return type
  • The constructor body should not return a value
  • Whenever a programmer develop a constructor, the compiler will not create a constructor
  • Whenever we create an instance, first the new operator create an instance and invokes the constructor to build the instance
  • Always constructor must be non-static context
  • When we want common features for all instances we can define inside a constructor

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?

  • What actually happens with the constructor is that the runtime uses type data generated by the compiler to determine how much space is needed to store an object instance in memory, be it on the stack or on the heap.
  • This space includes all members’ variables. After this space is allocated, the constructor is called as an internal part of the instantiation and initialization process to initialize the contents of the fields.
  • Then, when the constructor exits, the runtime returns the newly-created instance. So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime.
  • Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.
  • Constructor in java?is a?special type of method?that is used to initialize the object.
  • Java constructor is?invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Types of java constructors

There are two types of constructors:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

Java Default Constructor

A constructor that has no parameter is known as default constructor.

Syntax of default constructor:

  1. <class_name>(){}??

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

  • A constructor develop with argument is known as parameterized constructor or argument constructor
  • Constructors that have parameters are known as 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

  • Developing more than one constructor in a class with different argument list is known as “Constructor overloading”
  • Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
  • In order to develop constructor overloading following rules to be followed (Any one should be satisfied)

  1. The argument should differ
  2. The number of argument (length) should differ
  3. The position of the argument should differ?

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:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

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

  • While creating an instance, if we have to initialize instance than we develop constructor
  • At that instance creation time we can also perform certain operation which reduces the code.

Note:?

  1. If a class contain any constructor other than default then compiler will not create default constructor
  2. If a class contains overloaded constructor, java calls the constructor based on the argument list

This calling statement/call to this statement

  • We can call a constructor with in a constructor of its own class
  • Constructor of a class can call another constructor of same class using ‘this()’ statements
  • ‘this()’ statements must be used only in the constructor body and it should be the first statement
  • We can invoke an argument constructor using ‘this()’ statements
  • Java doesn’t support ‘recursive constructor call’
  • Inside a constructor body only one ‘this()’ statement is allowed

//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?

  1. Implicit parameters
  2. Explicit parameters

Implicit parameter:

  • The object on which the method is called is called as implicit parameters.
  • The data type of the implicit parameter is the class in which the method is defined

Ex: MyData

  • It is called implicit because we don’t mention it when we declare the method

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

  • Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
  • The ‘this’ reference always points to an object’s own instance. Any object can use the ‘this’ reference to refer to its own instance. Think of the words me, ‘myself’ and I: anyone using those words is always referring to themselves.

Use of this keyword

  • It clarify that you are talking about a field, when there is another variable of the same name. Some use this as a means to differentiate instance variables from local variables or method parameters.
  • Refer to current object as stated above
  • Invoke other constructor of the current class in your parameterized constructor.
  • It can be used to return the instance of a class
  • this can also be used to refer to the outer object

Note: One point to remember is that this is associated with the instance of the class, so it will not work in static methods

  • This keyword can be used inside any method to refer to the current object.
  • This is always a reference to the object on which the method is invoked.
  • Outside the class, the name of the calling object is known, ex: obj.display ().
  • Inside the class, the name of the calling object is not necessary, use ‘this’.
  • The keyword ‘this’ stores a reference to the current object who is calling the shots.
  • If a class has multiple constructors, it is better to implement them using the ‘this’ (list of arguments) as much as possible. In general, a constructor with no argument or fewer arguments can invoke the constructor with more arguments using this (list of arguments).
  • Simplifies coding and makes the class easier to read and to maintain.
  • Java provides a special keyword by name ‘this’.
  • ‘this’ keyword is used to refer the current instance members (non-static).
  • Always ‘this’ keyword will be having the address of current instance and object.
  • ‘this’ keyword is used to differentiate global and local variables.

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

  • In the above example, we have two variable with the same name in inside and outside the method, if we execute the above program the local variable value will be displayed because local variable will be always override the global variables, so in order to refer the global variables inside the method we use ‘this’ keyword.
  • ‘this’ lets us to refer directly to the object, you can use it to access instance (global) variable directly.?

class A1
{	
	int i =10;
	public void Display()
	{
	       int i = 20;
		System.out.println("i:"+i);
		System.out.println("i:"+this.i);
	}
}        

  • If we run the above example first statements will print the local variable name and second statements will print the instance or global variable value.

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:?

  1. The instance initializer block is created when instance of the class is created.
  2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super () constructor call).
  3. The instance initializer block comes in the order in which they appear.

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

要查看或添加评论,请登录

Srinivas Prasad K T的更多文章

社区洞察

其他会员也浏览了