Getting reference of Outer class members inside inner class
In the earlier posts, I explained about inner classes. To know about inner class please have a look in the below link.
Example for getting the reference of Outer Class members inside Inner class
GettingReferenceOfOuterInInner.java
package com.gaurav.corejava.innerclass;
public class GettingReferenceOfOuterInInner {
String strTest = "WELCOME";
int num = 100;
class inner{
public String testFunction(){
System.out.println("******************************************");
System.out.println("CALSS REFERENCE : - "+this);
System.out.println("GETTING INT INSTANCE VARIABLE : - "+GettingReferenceOfOuterInInner.this.num);
return strTest;
}
public String toString(){
return "MYSELF INNER CLASS REFERENCE OBJECT";
}
}
public static void main(String args[]){
GettingReferenceOfOuterInInner.inner inn = (new GettingReferenceOfOuterInInner()).new inner();
System.out.println("CALLING TEST FUNCTION OF INNER CLASS METHOD : - "+inn.testFunction());
}
}
public class GettingReferenceOfOuterInInner {
String strTest = "WELCOME";
int num = 100;
class inner{
public String testFunction(){
System.out.println("******************************************");
System.out.println("CALSS REFERENCE : - "+this);
System.out.println("GETTING INT INSTANCE VARIABLE : - "+GettingReferenceOfOuterInInner.this.num);
return strTest;
}
public String toString(){
return "MYSELF INNER CLASS REFERENCE OBJECT";
}
}
public static void main(String args[]){
GettingReferenceOfOuterInInner.inner inn = (new GettingReferenceOfOuterInInner()).new inner();
System.out.println("CALLING TEST FUNCTION OF INNER CLASS METHOD : - "+inn.testFunction());
}
}
Result:-
******************************************
CALSS REFERENCE : - MYSELF INNER CLASS REFERENCE OBJECT
GETTING INT INSTANCE VARIABLE : - 100
CALLING TEST FUNCTION OF INNER CLASS METHOD : - WELCOME
CALSS REFERENCE : - MYSELF INNER CLASS REFERENCE OBJECT
GETTING INT INSTANCE VARIABLE : - 100
CALLING TEST FUNCTION OF INNER CLASS METHOD : - WELCOME
No comments:
Post a Comment