please give me more examples on inner clases | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

please give me more examples on inner clases

18th Aug 2016, 1:46 PM
Majharoddin
2 Answers
+ 8
/*John Is A father And Ron is his son as defined below... Start Reading Code from main() method. "Father John =new Father();" creates object of class father hence method shw(); [defined in class Father] becomes accesible from main() through Object 'John' hence We can call John.shw(); Similarly in shw(); Object Of class Son Is defined By "Son Ron=new Son();" hence we can call 'show_age()' method from method shw(); hence we get an output "Sons Age is 20" Now look at the next statement in main method [which is in comments i.e [Son object = new Son();] here compiler gives an error as class Son is not local to method 'main()'[i.e Not accessible from main as it is inner class] but the same statement in 'shw()' method executes without an error that is because class Son is accessible from class father. */ public class Father { private void shw() { Son Ron=new Son(); Ron.show_age(); } /*Inner Class*/ public class Son { int s_age=20; void show_age() { System.out.println("Sons Age is " + s_age ); } } public static void main(String[] args) { Father John =new Father(); John.shw(); /*Son object = new Son(); object.show_age();*/ } }
18th Aug 2016, 5:20 PM
Hardik Raut
Hardik Raut - avatar
+ 2
There are three types of inner classes - Inner Class - Method-local - Anonymous Inner Class To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the object of the outer class, you can instantiate the inner class public class Outer{ public class Inner{ // this is Inner Class } } class MyProgram{ public static void main(String [] args){ Outer o = new Outer(); Outer.Inner inn = outer.new Inner(); } } Method-local method-local inner class can be instantiated only within the method. class Outer{ void methodA(){ class Inner{ } Inner in = new Inner(); } } Anonymous an inner class declared without a class name abstract class AnonymousInner{ public abstract void mymethod(); } public class Outer { public static void main(String args[]){ AnonymousInner inner = new AnonymousInner(){ public void mymethod(){ System.out.println("anonymouse inner"); }}; inner.mymethod(); } }
18th Aug 2016, 4:29 PM
WPimpong
WPimpong - avatar