Why do we use the "this" keyword?
Hi guys,
I am studying for a test, and one of sections is on inheritance.
And I really don't understand how the "this" keyword works.
From what I have read, this just references the active variable/object.
So for example, why is "this" used in the below code?
Such as with this.pages = pages;
and with this.definitions = definitions;
Code Java:
/**
* Words.java - Demonstrates the use of the super reference..
*
* @author Lewis/Loftus
* @version 2nd ed.
*/
public class Words2
{
//-----------------------------------------------------------------
// Instantiates a derived class and invokes its inherited and
// local methods.
//-----------------------------------------------------------------
public static void main ( String[] args )
{
Dictionary2 webster = new Dictionary2( 1500, 52500 );
webster.pageMessage();
webster.definitionMessage();
}
}
Code Java:
/**
* Book.java - represents a book.
*
* @author Lewis/Loftus
* @version 2nd ed.
*/
public class Book2
{
protected int pages;
/**
* constructor
*
* @param int (pages)
*/
public Book2( int pages )
{
this.pages = pages;
} // constructor
/**
* pageMessage - prints a message concerning the pages of this book.
*/
public void pageMessage()
{
System.out.println( "Number of pages: " + pages );
} // method pageMessage
} // class Book
Code Java:
/**
* Dictionary2.java - represents a dictionary, which is a book
*
* @author Lewis/Loftus
* @version 2nd ed.
*/
public class Dictionary2 extends Book2
{
private int definitions;
/**
* constructor
*
* @param int (pages)
* @param int (definitions)
*/
public Dictionary2( int pages, int definitions )
{
super( pages );
this.definitions = definitions;
} // constructor
/**
* definitionMessage - prints a message using both local and inherited
* values
*/
public void definitionMessage()
{
System.out.println("Number of definitions: " + definitions);
System.out.println("Definitions per page: " + definitions/pages);
} // method definitionMessage
} // class Dictionary (extends Book2)
Re: Why do we use the "this" keyword?
this references the 'current' object (see Using the this Keyword (The Java™ Tutorials > Learning the Java Language > Classes and Objects)). It is useful in many situations, one of which is in the code you posted. For example, imagine the following scenario
Code java:
public Dictionary2( int pages, int definitions )
{
super( pages );
definitions = definitions;//bad code design
} // constructor
In the above example, the parameter definitions will be set to itself (a pretty useless line of code) while the object variable definitions never gets initialized as intended