Programming Tutorials

How to access instance from an inner class and accessing outer class variables in java

By: Saravanan in Java Tutorials on 2009-10-03  

In this Tutorial we are going to see how to access instance from an inner class and access outer class variables. First we are going to see the example of accessing instance from an inner class

// Accessing its enclosing instance from an inner class

public class MainClass
 {
  private int vlaue = 9;

  public MainClass()
  {

    InnerClass inner = new InnerClass();
    inner.printValue();
  }

  class InnerClass
  {

    public void printValue()
    {

      System.out.println(MainClass.this.value);
    }
  }

  public static void main(String[] args)
  {
    new MainClass();
  }
}

  //This is the accessing outer class variables in java.
public class MainClass
 {
  int c = 0;

  public class counter
  {
    int c = 10;

    public void increaseCount()
    {
      c++;
      MainClass.this.c++;
    }

    public void displayCounts()
    {
      System.out.println("Inner: " + c);
      System.out.println("Outer: " + MainClass.this.c);
    }
  }

  public void dowork()
  {
    counter ct = new counter();
    ct.increaseCount();
    ct.increaseCount();
    ct.increaseCount();
    ct.displayCounts();
  }

  public static void main(String args[])
  {
    MainClass mc = new MainClass();
    mc.dowork();
  }
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)