Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Anderstanding "this" in java

843785Oct 1 2008 — edited Oct 2 2008
Hello guys,

I am learning java in school now and i am strugling to anderstand "this" function in java. Here is somthing i saw my professor do and maybe you can break it down for me.

This is just a part of the class with constructor set up. As you can see in the second constructor he used this(10) and my anderstanding is that value is to be used when no "initCapacity" is provided. I have used JUnit and set up a test case, and that seems to be true. However i want to know what happens there when he used "this" why could he not have just decleared "initCapacity = 10" in second constructor, that would have done the job just as good as what he used??

This is just one example i have seen this used on objects too and variables and i just cant get my mind around it, i hope you guys can clear this up for me.
public class MStack
{
  private Object[] elems;
  private int size;
  
  public MStack(int initCapacity) {
    elems = new Object[initCapacity];
    size = 0;
  }

  public MStack() {
    this(10);
  }
}
Thank you for all your help,

-Lovac
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 30 2008
Added on Oct 1 2008
32 comments
538 views