Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2006

Tip: Looking for answers? Try searching our database.

the meaning of 'this'

Thread view: 
charles hottel - 24 Mar 2006 23:52 GMT
Hi to all!

I am new to Java and have run into something confusing to me.

I know that 'this' can refer to the current object but what does 'this' mean
when used inside a constructor before the object has been completely
created?  Specifically the book I am reading has the following example:

There is a DiscountBookOrder class that extends a BookOrder class. Both
classes have a 'total' field and a 'setTotal()' method and the constructors
of both classes invoke a 'setTotal()' method.  The DiscountBookOrder
constructor invokes the BookOrder constructor and I have found that the call
to 'setTotal()' in the BookOrder constructor actually invokes the
'setTotal()' method in the DiscountBookOrder class. This was somewhat
confusing at first but understandable since the method is overridden. I
experimented by changing the call in the BookOrder constructor to
'this.setTotal()' thinking that the 'setTotal()' method in BookOrder would
be the one used, but adding the 'this' did not cause any difference. At this
point in the execution sequence neither the DiscountBookOrder object nor the
BookOrder object is fully created yet a 'this' reference to
DiscountBookOrder clearly exists. At exactly what point did it come into
being?  Why does 'this' within the BookOrder constructor refer to a
DiscountBookOrder object? Also how would I change the code in the BookOrder
constructor to invoke BookOrder 'setTotal()' method? At this point there is
no BookOrder object to use to invoke the method. I would also appreciate any
comments about this design i.e. is this a typical thing to do?  Also I
really do not like the variable names that they used and I think that the
'total' field in the DiscountBookOrder class should at least be changed to
'discountTotal'. Is it typical to use the same variable names in a class and
its superclass?

This seems kind of confusing for a first example of inheritance. I wonder if
it was intentional or a mistake. I mean maybe the author did not realize
that this was happening. Maybe it is just because this is still a new
concept to me.

Below is the code with the irrelevant (I hope) bits snipped out. I can post
the whole thing if necessary. Thanks in advance for you comments and help.

public class DiscountBookOrder extends BookOrder{
  private String discountCode;
  private double subtotal, percentOff, total;

  public DiscountBookOrder(String bookCode, int bookQuantity, String
keyCode){
     super(bookCode, bookQuantity);
     discountCode = keyCode;
     setPercentOff();
     setTotal();
  }

  public void setPercentOff(){
     if (discountCode.equalsIgnoreCase("a10"))
        percentOff = 0.1;
     else
        percentOff = 0.0;
  }

  public void setTotal(){
           System.out.println("DiscountBookOrder.setTotal");  //test
     subtotal = super.getQuantity() * super.getBook().getPrice();
     total = subtotal - (subtotal * percentOff);
          System.out.println(subtotal);  //test
          System.out.println(total);  //test
  }

//*******************************************************************************************************

public class BookOrder{
  private Book book;
  private int quantity;
  private double total;

  private static int orderObjectCount = 0;

  public BookOrder(String bookCode, int bookQuantity){
     book = new Book(bookCode);
     quantity = bookQuantity;
             // System.out.println(quantity); //test
             // System.out.println(book.getPrice());  //test
             //when this constructor is invoked from DiscountBookOrder then
the method invoked
             //next is the setTotal in DiscountBookOrder even if you change
it to
            //this.setTotal(). This leaves BookOrder.total initialized to
zero
     setTotal();
            //System.out.println(total);  //test
     orderObjectCount++;
  }

  public void setTotal(){
           System.out.println("BookOrder.setTotal"); //test
     total = quantity * book.getPrice();
  }
Roedy Green - 24 Mar 2006 23:58 GMT
On Fri, 24 Mar 2006 17:52:35 -0500, "charles hottel"
<jghottel@yahoo.com> wrote, quoted or indirectly quoted someone who
said :

>I know that 'this' can refer to the current object but what does 'this' mean
>when used inside a constructor before the object has been completely
>created?  Specifically the book I am reading has the following example:

see http://mindprod.com/jgloss/this.html

It should tell you more than you wanted to know about "this".
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Hal Rosser - 25 Mar 2006 04:31 GMT
> Hi to all!
>
[quoted text clipped - 61 lines]
>            System.out.println(total);  //test
>    }

//**************************************************************************
*****************************

> public class BookOrder{
>    private Book book;
[quoted text clipped - 23 lines]
>       total = quantity * book.getPrice();
>    }

Looks like you're using Murach's Beginning Java 2 and it looks like you're
into chapter 5.
"this" - in the constructor - refers to the object which the constructor
will be creating when it is called.
Notice the first line in the DiscountBookOrder constructor makes a call to
"super" - which is a call to the BookOrder constructor - all code in the
super class also belongs to the child class. (A DiscountBookOrder object <is
a> BookOrder.)
You can consider all methods and variables of the BookOrder class is also a
part of the DiscountBookOrder class because DiscountBookOrder extends
BookOrder.
You're asking for comments on the design - Its a good text - they designed
the classes as examples - to demonstrate object-oriented principles.   Many
would agree that different variable names could have been chosen - but don't
use that as an excuse to 'not learn' the principles in those chapters.
 IF you can survive Chapters 4, 5, and 6 , then you will have a good grasp
on Object-Oriented programming.
I would also recommend another book to accompany that one (Head First Java -
by Bert Bates and  Kathy Sierra) .
Bjorn Abelli - 25 Mar 2006 11:35 GMT
"charles hottel" wrote...

> I know that 'this' can refer to the current object but what does
> 'this' mean when used inside a constructor before the object has
> been completely created?

It still means the current object from within "this" is used.

> I experimented by changing the call in the
> BookOrder constructor to 'this.setTotal()' thinking that the
> 'setTotal()' method in BookOrder would be the one used, but
> adding the 'this' did not cause any difference.

"this" still refers to the same object, even when it's used in a method in a
super class to the class of the instance.

That it calls the overridden method is due to polymorphism.

> At this point in the execution sequence neither the DiscountBookOrder
> object nor the BookOrder object is fully created yet a 'this' reference
> to DiscountBookOrder clearly exists.

There's only *one* object here!
An instance of DiscountBookOrder (which is an extension to BookOrder).

> At exactly what point did it come into being?

It "came into being" when you did "new DiscountBookOrder(...)", however not
fully initialized yet.

> Why does 'this' within the BookOrder constructor refer to a
> DiscountBookOrder object?

Because the instance *is* a DiscountBookOrder object.

> Also how would I change the code in the BookOrder constructor to invoke
> BookOrder 'setTotal()' method?

If you want that to happen when instantiating a DiscountBookOrder object,
simply don't override it.

If you create a BookOrder instance instead of a DiscountBookOrder instance,
the BookOrder method will be used.

> At this point there is no BookOrder object to use to invoke the method.

Well, there is...

A DiscountBookOrder instance "is-a" BookOrder object too.

> I would also appreciate any comments about this design i.e.
> is this a typical thing to do?  Also I really do not like
> the variable names that they used and I think that the 'total' field in
> the DiscountBookOrder class should at least
> be changed to 'discountTotal'. Is it typical to use the same
> variable names in a class and its superclass?

Well, to the subclass, the BookOrder class only looks like this:

public class BookOrder {

  public BookOrder(String bookCode, int bookQuantity);

  public void setTotal();
  public double getQuantity();
  public Book getBook();

  // ...and possibly more public and protected methods and attributes
  // that you didn't provide here...

}

That means that there *isn't* a field "total" in the superclass from the
subclass' perspective.

> This seems kind of confusing for a first example of inheritance.
> I wonder if  it was intentional or a mistake. I mean maybe the
> author did not realize that this was happening. Maybe it is just
> because this is still a new concept to me.

This is probably fully intentional of the author, to illustrate

- subclassing  ( DiscountBookOrder extends BookOrder)
- overriding   ( setTotal() )
- polymorphism ( e.g. invoking the subclass method when it's overridden)

As an example of those concepts it works, even if I wouldn't write them that
way in production code.

// Bjorn A
BWill - 25 Mar 2006 21:37 GMT
The basic point is that calling the parent constructor within a
constructor is a special case recognized by the language (in fact, the
rule is that calling the parent constructor must be the first thing done
in a constructor). So the answer to your question is, what object 'this'
refers to depends upon the object being constructed:

new BookStore(...);

/* the 'this' reference in the BookStore constructor refers to the
BookStore object being created */

new DiscountBookStore(...);

/* the 'this' reference used in the DiscountBookStore constructor refers
to the DiscountBookStore object being constructed, and when that
constructor calls the constructor of its parent, 'this' in the parent
constructor also refers to the DiscountBookStore object being constructed */

If this was not apparent, a clue is that the call to the parent
constructor in DiscountBookStore() does not use the keyword 'new'
because it is not constructing a new, different object but rather the
very same object already under construction. (I suppose this is one
justification for the unnecessary new keyword.) So remember, a
constructor always begins with a call to a constructor of the parent
class (if such a call is omited, Java calls the parameterless
constructor of the parent implicitly; you'll get a compile error if you
leave out any call to the parent when the parent doesn't have a
parameterless constructor).
Roedy Green - 26 Mar 2006 00:07 GMT
>(in fact, the
>rule is that calling the parent constructor must be the first thing done
>in a constructor). So the answer to your question is, what object 'this'
>refers to depends upon the object being constructed:

Just to clarify, when you use super( ... ) you are calling the
constructor of the superclass. When you call this( ) you are calling
one of the other constructors of THIS class.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.