Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Use the Java Keyword this

The keyword this in Java refers to the current class instance. For example, if a class defines a method named Calculate, you can call that method from another method within the same class like this:

    this.Calculate();

Of course, you can also call the Calculate method without the this keyword:

    Calculate();

Thus, in most cases, the keyword this is not necessary.

However, sometimes the this keyword can come in handy. For example:

public class Actor
{
    string lastName;
    string firstName;
    public Actor(String lastName, String firstName)
    {
        this.lastName = lastName;
        this.firstName = firstName;
    }
}

The this keywords are required to distinguish among the parameters named lastName and firstName and the instance.

Sometimes, you use the this keyword by itself to pass a reference to the current object as a method parameter. You can print the current object to the console by using the following statement:

System.out.println(this);

The println method calls the object’s toString method to get a string representation of the object and then prints it to the console. By default, toString prints the name of the class that the object was created from and the object’s hash code. If you want the println method to print something more meaningful, provide a toString method of your own for the class.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!