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;
/** * 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(); } }
/** * 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
/** * 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)