Using the Keyword "This" in Java

Why is the using of 'this' keyword necessary?

What advantage does it have over passing the object itself since the
method is going to access the current object that is being passes
anyway.

As per your question on advantage of using this keyword over passing the object itself is this is a final variable in Java whereas the object when passed may or may not be final. Being a final variable, I can clearly see 2 main advantages of using this over passing object itself.

  1. One cannot assign any new value to the current instance of this.

    this = new Foo(); //compilation error; cannot assign value to final variable : this

  2. It can be used in synchronized block.

    synchronized(this){
    /*this synchronized block will be locked on current instance*/
    }

Apart from this context set up in the question, there are many advantages of using this in Java which you can figure out from other answers.

Shishir

Use of this keyword in java

this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):

class Foo
{
private int bar;

public Foo() {
this(42); // invoke parameterized constructor
}

public Foo(int bar) {
this.bar = bar; // disambiguate
}

public void frob() {
this.baz(); // used "just because"
}

private void baz() {
System.out.println("whatever");
}

}

Does Java have a using statement?

Java 7 introduced Automatic Resource Block Management which brings this feature to the Java platform. Prior versions of Java didn't have anything resembling using.

As an example, you can use any variable implementing java.lang.AutoCloseable in the following way:

try(ClassImplementingAutoCloseable obj = new ClassImplementingAutoCloseable())
{
...
}

Java's java.io.Closeable interface, implemented by streams, automagically extends AutoCloseable, so you can already use streams in a try block the same way you would use them in a C# using block. This is equivalent to C#'s using.

As of version 5.0, Hibernate Sessions implement AutoCloseable and can be auto-closed in ARM blocks. In previous versions of Hibernate Session did not implement AutoCloseable. So you'll need to be on Hibernate >= 5.0 in order to use this feature.

Using the keyword this in java

The this keyword is a reference to the current object.

class Foo
{
private int bar;

public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}

Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.

If you were to reference objects that are intrinsically yours you would say something like this:

My arm or my leg

Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:

class Foo
{
private int bar;

public Foo(int bar)
{
my.bar = bar;
}
}

Java: Problems with this keyword

Since you are using this in a static context it is giving you the error. Try the following code:

package myLib;

class Book {
// Declare fields
byte iStatus;
int iPages;
String sTitle, sAuthor;
String sBorrowedBy, sReservedBy;
String sDueDate, sReturnDate;

public static final byte BORROWED = 0, AVAILABLE = 1, RESERVED = 2;

// Constructor
public Book(String Title, String Author, int Pages) {
this.sTitle = Title;
this.sAuthor = Author;
this.iPages = Pages;
this.iStatus = Book.AVAILABLE;
}

// Borrow method
//Remove the static keyword
//Refer to the remaining static variables like AVAILABLE OR BORROWED using Book and not this keyword.
void borrowBook(String Borrower, String Due) {
if(this.iStatus == Book.AVAILABLE) {
this.sBorrowedBy = Borrower;
this.sDueDate = Due;
this.iStatus = Book.BORROWED;
}
else if(this.iStatus == Book.RESERVED && this.sReservedBy == Borrower) {
this.sBorrowedBy = Borrower;
this.sDueDate = Due;
this.sReservedBy = "";
this.iStatus = Book.BORROWED;
}

}
}

using keyword this with multiple constructors in a Class

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

If you do

new Rational()

the empty constructor will be called. This constructor will then call the constructor with one argument, i.e.

new Rational(0)

which again will call

new Rational(0,1)

That last constructor will then set the instance variables.


For further information look at this tutorial.

Also interesting: Java Language Specification

Java - when to use 'this' keyword

but Java is clever enough to know what is happening if I change the statement in the constructor to

  bar = bar;

FALSE! It compiles but it doesn't do what you think it does!

As to when to use it, a lot of it is personal preference. I like to use this in my public methods, even when it's unnecessary, because that's where the interfacing happens and it's nice to assert what's mine and what's not.

As reference, you can check the Oracle's Java Tutorials out about this.subject ;-)

http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Java using this keyword inside a thread created inside a class

You could use Runnable to avoid this keyword conflict.



Related Topics



Leave a reply



Submit