Java pass this object

Passing and Returning Objects in Java

Although Java is strictly passed by value, the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does this interesting thing that’s sort of a hybrid between pass-by-value and pass-by-reference.
Basically, a parameter cannot be changed by the function, but the function can ask the parameter to change itself via calling some method within it.

  • While creating a variable of a class type, we only create a reference to an object. Thus, when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.
  • This effectively means that objects act as if they are passed to methods by use of call-by-reference.
  • Changes to the object inside the method do reflect the object used as an argument.

Illustration: Let us suppose three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:

ObjectPassDemo ob1 = new ObjectPassDemo(100, 22); ObjectPassDemo ob2 = new ObjectPassDemo(100, 22); ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

Passing Objects as Parameters and Returning Objects

From the method side, a reference of type Foo with a name a is declared and it’s initially assigned to null.

boolean equalTo(ObjectPassDemo o);

Passing Objects as Parameters and Returning Objects

As we call the method equalTo, the reference ‘o’ will be assigned to the object which is passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following statement execute.

System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));

Passing Objects as Parameters and Returning Objects

Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean true will be return.

Читайте также:  What is set in python

Again ‘o’ will reassign to ‘ob3’ as the following statement execute.

System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));

Passing Objects as Parameters and Returning Objects

  • Now as we can see, the equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’. Since values of ‘a’ and ‘b’ are not the same for both the references, so if(condition) is false, so else block will execute, and false will be returned.

In Java we can pass objects to methods as one can perceive from the below program as follows:

Источник

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

Using this with a Field

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

For example, the Point class was written like this

but it could have been written like this:

Each argument to the constructor shadows one of the object’s fields — inside the constructor x is a local copy of the constructor’s first argument. To refer to the Point field x , the constructor must use this.x .

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here’s another Rectangle class, with a different implementation from the one in the Objects section.

public class Rectangle < private int x, y; private int width, height; public Rectangle() < this(0, 0, 1, 1); > public Rectangle(int width, int height) < this(0, 0, width, height); > public Rectangle(int x, int y, int width, int height) < this.x = x; this.y = y; this.width = width; this.height = height; >. >

This class contains a set of constructors. Each constructor initializes some or all of the rectangle’s member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor creates a 1×1 Rectangle at coordinates 0,0. The two-argument constructor calls the four-argument constructor, passing in the width and height but always using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number and the type of arguments.

If present, the invocation of another constructor must be the first line in the constructor.

Источник

This Keyword in Java

«This» keyword in java is one of the most used and very important keywords.
«This» keyword in java is used to refer current class objects.
We can use this keyword to access current class object members.

Image of boy for understanding this keyword in java

So you might be wondering if we can access the current class member directly, Why do we need this keyword?

One of the answer is that, if we have same name for method level and class level variable, then there is an ambiguity for JVM. JVM can not use class variable and uses the local variable by default. In such a case we can use «this» keyword for referring the class level variable.

6 uses of «this» keyword in java

  1. Accessing class level variable
  2. Accessing class methods — default
  3. For calling other constructor of same class
  4. Using ‘this’ keyword as return value
  5. Passing ‘this’ keyword as argument to method
  6. Passing this keyword as argument to constructor

1. Accessing class level variable

Assessing class level variable using this keyword is the most common use of «this» keyword.

Most of the time we create some variable in class, then we can set the value from constructor or setter method. If we use same name for argument variable and class level variable then jvm will use local variable always, and it will not set the value to class level variable

lets take a look at example for better understanding,

public class Country< private String name; public Country(String name)< Wrong: name = name; Right: this.name = name; data-lazy-src=

3. For calling other constructor of same class

«This» keyword in java can be used to call other constructor of same class.

Some times we have different constructors with different parameters then you can reuse existing constructor using «this» keyword.
We can call any type of constructor within any constructor. That is we can call default in parameterized, parameterized in defatul or parameterized in parameterized constructor.

The most important thing to note is that the use of «this» for calling other constructor should be the first line in constructor.

Let’s assume we have a class, let’s call it SomeClass. In this class we have a default constructor and a constructor with variable.
There is some default code that is required for at object creation. So we have added this code in default constructor.
Now we need the same code from default constructor in parameterized constructor. So in this case we can call default constructor from another constructor using this();

public class SomeClass < private int variable ; public SomeClass()< // some code. >public SomeClass(int variable ) < this() this.variable = variable ; >>

Lets take look at real life examples for shape class. In this class we have length and breadth variables. we need two constructors.
Fist constructor will take two arguments for length and breadth.
Second constructor will take only one argument, this will be same value for length and breath.

public class Shape < private int length ; private int breadth; public Shape(int length ,int breadth)< this.length = length ; this.breadth = breadth; >public Shape(int length ) < this(length,length); >>

In above examples we are reusing constructors using «this» keyword in java.

4. Using «this» keyword as return value in java

If you need to return current object instance we can use «this» keyword.
Builder design pattern is one of the most common example of this case.

Let’s look at an example for better understanding,

public class MenuBuilder < Listmenus = new ArrayList<>(); public MenuBuilder withAdd() < menus.add(new Menus("Add")) return this; >>

As you can see in the above example, we used «this» as return value in withAdd() Method. In above example withAdd() method returns the current class object.

5. Passing «this» keyword as argument to method

If we want to call some method and the method needs current class object as argument, we can use this keyword to pass the current class object instance.

We can pass this as argument to current class as well as another class methods.

public class City < private String name; private Country country; public City(String name)< this.name= name; >public void setCountry(Country country) < this.country = country; >> public class Country < private City capital; public void setCapital(String cityName)< City capital = new City(cityName); // passing country class object using this keyword capital.setCountry(this); this.capital = capital; >>

As shown in the above example, we have City and Country class. In City class setCountry() method needs object of Country class. So we have passed Country class instance using «this» keyword from Country class.

6. Passing «this» keyword as argument to constructor

Similar to passing as argument to another method we can also pass «this» keyword as argument to constructor of another class.

We can pass this as argument to constructor of current class as well as to constructor of another class.

public class City < private String name; private Country country; public City(String name, Country country)< this.name= name; this.country = country; >> public class Country < private City capital; public void setCapital(String cityName)< // passing country class object using this keyword City capital = new City(cityName,this); this.capital = capital; >>

As shown in the above example, we have City and Country class. In City class constructor needs object of Country class. So we have passed Country class instance using «this» keyword from Country class.

Fast track reading

  • This keyword in java is used to refer current class objects
  • Using this keyword we can access current class instance variable, methods, or constructor
  • We can pass this keyword as argument to another method or constructor
  • We can return current class instance using this keyword

Related topics

Java pass this object

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Оцените статью