vivarem logo
/ Vivarem / Computers and IT / IT Education / online / tutorial / Java / OOP / 7 /
There are 0 sub sections

You can add Your Link here with New Link
Java Object Oriented Programming - 7

Inner classes
Java supports inner classes where by you are able to define inner classes within another class.It may be inside a member function or with in the class.The outer class datamemebers are available for the innerclass as it is available for the innerclass.If the inner class and outer class have a datamemeber of the same name the innerclass can access the inner class by OuterClassName.this.datamember.To invoke an Inner Class from outside the class, creation of outer class object is necessary The following syntax may be used.

e.g.
Outer o=new Outer();
Outer.Inner in=o.new Inner();

Method Local Inner Classes
Inner class can be defined inside a member function in that case the class should be instantiated with in the function, this object is available only within that particular member function. The syntax is similar to any ordinary object creation, InnerClassName ic=new InnerClassName();
example

package com.vivarem.examples;
public class JavaInner{
String name="vivarem.com";

public class MyInner{
int a,b;

public MyInner(int a,int b){
this.a=a;
this.b=b;
}
public int sum(){
return a+b;
}
public int multi(){
return a*b;
}
String name="sss";
public void showOuterName(){
System.out.println("Outer Class Data from Inner Class "+JavaInner.this.name);
}
}
public void sampleFunction(){
class AnotherInner{
public void show(){System.out.println(" from Method Local Inner Class");

}

}
AnotherInner ai= new AnotherInner();
ai.show();
}
public void callInner(){
MyInner m=new MyInner(20,30);
System.out.println("from Outer class Sum="+m.sum());
}
public static void main(String[] s){
JavaInner ji=new JavaInner();//create outer class
ji.callInner();//this method creates an inner class instance from a method
JavaInner.MyInner mi= ji.new MyInner(1,10);//create innerclass instance from outside
System.out.println(mi.sum());//invoke the inner class method sum?()
mi.showOuterName();//this method shows accessing outer class data memeber
ji.sampleFunction();//this method displays instantiating the inner method local class
}
}

< Inheritance |
Content |
Abstract Classes and Interfaces >


You can Add a Classified here with New Classified