How to access instance from an inner class and accessing outer class variables in java
By: Saravanan Printer Friendly Format
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();
}
}
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Archived Comments
1. IN the above program at the line in ineerclass's p
View Tutorial By: Narasimha at 2009-10-14 06:30:26