Alex Rivera | Logout

Using the keyword "this" in java

Asked 2009-02-23T13:11:57.897
21

I'm trying to get an understanding of what the the java keyword this actually does. I've been reading Sun's documentation but I'm still fuzzy on what this actually does.

Edit
Report

1 Answer

1

It can be also a way to access information on the current context. For example:

public class OuterClass
{
  public static void main(String[] args)
  {
    OuterClass oc = new OuterClass();
  }

  OuterClass()
  {
    InnerClass ic = new InnerClass(this);
  }

  class InnerClass
  {
    InnerClass(OuterClass oc)
    {
      System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
      System.out.println("This class: " + this + " / " + this.getClass());
      System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
      System.out.println("Other way to parent: " + OuterClass.this);
    }
  }
}
answered 2009-02-23T13:51:48.613

Your Answer