0% found this document useful (0 votes)
84 views22 pages

Inner Class Notes

The document provides comprehensive notes on Inner Classes in Core Java, detailing different types such as Normal, Method Local, Anonymous, and Static Nested Classes. It explains how to access inner class methods from outer classes, the relationship between outer and inner classes, and the applicable modifiers for both. Additionally, it includes examples and scenarios to illustrate the concepts effectively.

Uploaded by

raj9301560
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
84 views22 pages

Inner Class Notes

The document provides comprehensive notes on Inner Classes in Core Java, detailing different types such as Normal, Method Local, Anonymous, and Static Nested Classes. It explains how to access inner class methods from outer classes, the relationship between outer and inner classes, and the applicable modifiers for both. Additionally, it includes examples and scenarios to illustrate the concepts effectively.

Uploaded by

raj9301560
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 22
Core Java with SCJP/ OCIP Notes By Durga Sir Inner Classes With SCIP / OCIJP Chapter 9: InnerClasses DURGA techn (Sun certified a Realtime Expert) Ex. IBM Employee Trained Lakhs of Students for last 14 years across INDIA India’s No.1 Software Training Institute DURGASOFT Www.durgasoft.com Ph: 9246212143 8096969696 7 | DURGASOFT, #202, 2"¥Fioor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes Agenda 41. Introduction, 2. Normal or Regular inner classes © Accessing inner class code from static area of outer class © Accessing inner class code from instance area of outer class © Accessing inner class code from outside of outer class © The applicable modifiers for outer & inner classes © Nesting of Inner classes 3. Method Local inner classes. 4, Anonymous inner classes Anonymous inner class that extends a class ‘Anonymous Inner Class that implements an interface ‘Anonymous Inner Class that define inside method arguments Difference between general class and anonymous inner classes Explain the application areas of anonymous inner classes ? 5. Static nested classes © Compression between normal or regular class and static nested class ? 6. Various possible combinations of nested class & interfaces © Class inside a class © interface inside a class © Interface inside a interface © Class inside a interface 7. Conclusions ‘+ Sometimes we can declare a class inside another class such type of classes are called inner classes. Diagram: ‘+ Sun people introduced inner classes in 1.1 version as part of "EventHandling” to resolve GUI bugs. ‘+ But because of powerful features and benefits of inner classes slowly the programmers starts using in regular coding also. + Without existing one type of object if there is no chance of existing another type of object then we should go for inner classes. ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes ‘Without existing University object there is no chance of existing Department object hence we have to define Department class inside University class. Example’ Example Without existing Bank object there is no chance of existing Account object hence we have to define Account class inside Bank class. Example: Example Without existing Map object there is no chance of existing Entry object hence Entry Interface Is define inside Map interface. Map Is a collection of key-value pairs, each key-value pair Is called an Entry. Example: Note : Without existing Outer class Object there is no chance of existing Inner class Object. Note: The relationship between outer class and inner class is not IS-A relationship and it is Has-A relationship. Based on the purpose and position of declaration all inner classes are divided into 4 types. They are: Normal or Regular inner classes Method Local inner classes ‘Anonymous inner classes Static nested classes. ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes Barco her anne If we are declaring any named class inside another class directly without static modifier such type of inner classes are called normal or regular inner classes. Example: class Outer { class Inner { } output: Examp! class Outer ( class Inner { ) public static void main(String[] args) { System.out.println("outer class main method") ; ) output: + Inside inner class we can't declare static members. Hence itis not possible to declare main() method and we can't invoke inner class directly from the command prompt. Examp! class Outer ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes class Inner { public static void main(string[] args) { system.out.printin("inner class main method") ; } ) Output: E:\scjp>javac Outer. java outer. java:5: inner classes cannot have static declarations public static void main(String[] args) Accessing inner class code from static area of outer class: Example: class outer i class Inner { public void methodone() { system.out.printin("inner class method") ; y } public static void main(string[] args) { } Accessing inner class code from instance area of outer cla: Example: class Outer { class Inner { public void methodone() { } system. out.printin("inner class method"); ) public void methodtwo() { Inner ew Inner (); ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes i.methodone () ) public static void main(String[] args) { Outer o=new outer(); o.methodTwo () ; } ) output: E:\scjp>javac Outer. java E:\scjp>java Outer Inner class method Accessing inner class code from outside of outer class: Example: class outer { class Inner { public void methodone() { } system.out.printin("inner class method"); ) ) class Test ( public static void main(String[] args) { ) new Outer()-new Inner () .methodone () ; ) output: Inner class method + From inner class we can access all members of outer class (both static and non- static, private and non private methods and variables) directly. Example: class outer { int x=10; static int y=20; class Inner{ ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes public void methodone() { system. out.println(x) ;//10 system. out.printin(y) ;//20 y } public static void main(string[] args) { new Outer().new Inner () .methodone() ; } + Within the inner class “this” always refers current inner class object. To refer current outer class object we have to use “outer class name. this Example: class Outer ( int x=10; class Inner { int x=100; public void methodone () { int x=1000; System. out _print1n(x) ;//1000 system. out.printin(this.x) ;//100 System. out.printin(Outer.this.x) ;//10 } ) public static void main(String[] args) { new Outer().new Inner () .methodOne() ; ) ‘The applicable modifiers for outer classes ar public default final abstract strictfp ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes But for the inner classes in addition to this the following modifiers also allowed. Diagram: Nesting of Inner classes : ‘We can declare an inner class inside another inner class WS es TE aa Sos + Sometimes we can declare a class inside a method such type of inner classes are called method local inner classes. + The main objective of method local inner class is to define method specific repeatedly required functionality. + Method Local inner classes are best suitable to meet nested method requirement. + We can access method local inner class only within the method where we declared it. That is from outside of the method we can't access. As the scope of method local inner classes Is very less, this type of Inner classes are most rarely used type of inner classes. Example: class Test ( public void methodone () { class Inner { public void sum(int i,int 3) { system.out.print1n("The sum:"+(i+j)); } y Inner isnew Inner(); i.sum(10,20); i. sum(100,200) ; i-sum(1000, 2000) ; ) public static void main(string[] args) { ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes ) output: new Test () .methodOne() ; The sum: 30 The sum: 300 The sum: 3000 If we are declaring inner class inside instance method then we can access both static and non static members of outer class directly. But if we are declaring inner class inside static method then we can access only static members of outer class directly and we can't access instance members directly. Example: class Test ( int x=10; static int y=20; public void methodone() { class Inner { public void method?wo () ( system. out.printin(x);//10 system. out.printIn(y) ://20 ) ) Inner isnew Inner () ; i.methodTwo () ) public static void main(string[] args) { } new Test () .methodone () ; Hf we declare methodOne() method as static then we will get compile time error saying "non-static variable x cannot be referenced from a static context". From method local inner class we can’t access local variables of the method in which we declared it. But if that local variable is declared as final then we won't get any compile time error. Example: class Test { int x=10; public void methodone() ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes int y=20; class Inner { public void methodtwo () { system. out.printin (x) ;//10 system. out.printin(y); //C. local variable y is accessed from within inner class; needs to be declared final. } } Inner i=new Inner(); i-methodTwo () + } public static void main(string[] args) { } new Test () .methodone() ; + If we declared y as final then we won't get any compile time error. + Consider the following declaration. class Test ( int i=10; static int public void methodone() { int k=30; final int 1=40; class Inner { public void methodtwo() { system. out.printin(i) ; system. out.printin(j system. out.printin(k) ; system. out.printin(1) ; /{/-->line 1 4 y Inner i=new Inner (); i.methodTwo () 7 } public static void main(string[] args) { new Test () methodone() ; 70 | DURGASOFT, #202,2" Floor HUDA Maitvanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes , Aline 1 which of the following variables we can access? ‘If.we declare methodOne() method as static then which variables we cam access at line 1 + If we declare methodTwoi) as static then we will get compile time error because We can't declare static members inside inner classes, + The only applicable modifiers for method local inner classes are: 1. final ‘2. abstract 3. strictfp + By mistake if we are declaring any other modifier we will get compile time error. nonymous inner classes: + Sometimes we can declare inner class without name such type of inner classes are called anonymous inner classes. + The main objective of anonymous inner classes ‘+ There are 3 types of anonymous inner classes 4. Anonymous inner class that extends a class. 2. Anonymous inner class that implements an interface. 3. Anonymous inner class that defined inside method arguments. “just for instant use”. Anonymous inner class that extends a class: class Popcorn ( public void taste() { system. out.print1n ("spici 5 } class Test ‘ public static void main(string[] args) ‘ PopCorn psnew PopCorn() { 71 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes public void taste() { system. out.println ("salty") ; } ye p.taste() ;//salty PopCorn pl=new PopCorn() pl. taste () ;//spicy } Analysi 1. PopCorn p=new PopCorn(; We are just creating a PopCorn object. 2. PopCorn p=new PopCorn() 3.4 4d; 5. We are creating child class without name for the PopCorn class and for that child class we are creating an object with Parent PopCorn reference. 6. PopCorn p=new PopCorn() 7.4 8. public void taste() 9. { 10. system. out.printin ("salty") ; 11. ¥ 12. he 13. 1. We are creating child class for PopCorn without name. 2. We are overriding taste() method. 3. We are creating object for that child class with parent reference. te: Inside Anonymous inner classes we can take or declare new methods but outside of anonymous inner classes we can't call these methods directly because we are depending on parent reference.[parent reference can be used to hold child class object but by using that reference we can't call child specific methods]. These methods just for internal purpose only. Example class Popcorn ‘ public void taste() ‘ System. out.printin ("spicy") ; ) ) class Test ‘ public static void main(string[] args) 72 | DURGASOFT, #202,2" Floor RUDA Maitvanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes PopCorn p=new PopCorn () 4 public void taste() { methodOne() ;//valid call (internal purpose) system. out.printin ("salty") ; } public void methodone() ¢ system. out.printIn("child specific method") ; } ye //p.methodone() ;//here we can not call (outside inner class) p.taste() ;//salty PopCorn pl=new PopCorn() ; pl.taste() ;//spicy ) ) output: Child specific method Salty spicy Example 2: class Test ‘ public static void main(string[] args) ‘ Thread t=new Thread() ‘ public void run() { for(int i: { i<10;i++) system. out.println ("child thread") ; y be t.start(); for(int i=0;i<10;i++) { } System. out.println("main thread" 73 | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes Example: class InnerClassesDemo ( public static void main(String[] args) { Runnable r=new Runnable() //here we are not creating for Runnable interface, we are creating implements class object. public void run() { for(int i=0;i<10;i++) { system. out.printin ("Child thread"); + be Thread t t.start(); for(int i=0;i<10;i++) { } ew Thread(r) ; system.out.printin("Main thread") ; Anonymous Inner Class that define inside method argument: Example: class Test ‘ public static void main(String[] args) ‘ new Thread( new Runnable () ‘ public void run() ‘ for(int i=0;i<10;i++) ( 74 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes system. out.println ("child thread"); y } }) start(); for(int i=0;i<10;i++) { System.out.printin("main thread") ; + } ) output: + This output belongs to example 2, anonymous inner class that implements an interface example and anonymous inner class that define inside method arguments example. Main thread Main thread Main thread Main thread Main thread Main thread Main thread Main thread Main thread Main thread Child thread Child thread Child thread Child thread Child thread Child thread Child thread Child thread Child thread Child thread Difference between general class and anonymous inner classes: General Class ‘Anonymous Inner Class 4) Ageneral class can extends only one 1) Ofcource anonymous inner class also can class at a time. extends only one class at a time. 2) Ageneral class can implement any 2) But anonymous inner class can implement no. Of interfaces at a time. ‘only one interface at a time. 3) Ageneral class can extends a class 3) But anonymous inner class can extends a class and can implement an interface ‘or can implements an interface but not both 75 | DURGASOFT, #202,2" Floor HUDA Maitrvanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes simultaneously. simultaneously. 44) In normal Java class we can write 4) But in anonymous inner class we can't write constructor because we know name of constructor because anonymous inner class not ‘the class. having any name. ‘ ri ‘ > anonymous inner classes are best suitable to define call back functions in GUI components import java.awt.*; import java.awt.event.*; public class AnonymousInnerClassDemo { public static void main(String args[]) { Frame f=new Frame () ; £. addWindowListener (new WindowAdaptor () { public void windowClosing(WindowEvent e) { system.exit (0); } ne f£.add(new Label ("Anonymous Inner class Demo !!!")); £.setSize (500,500) ; f.setVisible (true) ; ) , Without Anonumous Inner class class GUI extends JFrame implements ActionListener { gButton bi,b2,b3,b4; public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { //perform bl specific functionality } else if (e.getSource==b2) { //perform b2 specific functionality 7 | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes With Anonumous Inner class class GUI extends JFrame { gButton b1,b2,b3,b4 ; bi.addActionListener(new Actionbistener() { public void actionPerformed(ActionEvent e) { //perform bl specific functionality + We b2.addActionListener (new ActionListener () { public void actionPerformed(ActionEvent e) { //perform b2 specific functionality Pel se Races + Sometimes we can declare inner classes with static modifier such type of inner classes are called static nested classes. ‘+ Inthe case of normal or regular inner classes without existing outer class object there is no chance of existing inner class object. ice., inner class object is always strongly associated with outer class object. ‘+ But in the case of static nested class without existing outer class object there may be a chance of existing static nested class object. Le., static nested class object is not strongly associated with outer class object. Example: class Test { static class Nested { public void methodone() { } ) public static void main(String[] args) system.out.printIn("nested class method") ; 77 | DURGASOFT, #202,2" Floor RUDA Maitvanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes Test.Nested t=new Test.Nested() ; t.methodone() ; ‘+ Inside static nested classes we can declare static members including main() method also. Hence it is possible to invoke static nested class directly from the command prompt. Examp class Test { static class Nested { public static void main(String[] args) { system.out.printin("nested class main method") ; y ) public static void main(String[] args) { system.out.println("outer class main method") ; } ) Output: E:\SCOP>javac Test. java E:\SCJP>java Test Outer class main method E:\SCOP>java Test§Nested Nested class main method + From the normal inner class we can access both static and non static members of. outer class but from static nested class we can access only static members of outer class. Example: class Test ( int x=10; static int y=20; static class Nested { public void methodone() { system. out.printin(x) ;//C.E:non-static variable x cannot be referenced from a static context 7g | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes system. out.println(y) ) } Sica ern ne eee inner class ‘Normal /regul 1) Without existing outer class object ‘there is no chance of existing inner class object. That Is inner class object is always associated with outer class object. 2) Inside normal or regular inner class we can't declare static members. 3) Inside normal inner class we can’t declare main() method and hence we can't invoke regular inner class directly from the command prompt. 4) From the normal or regular inner class ‘we can access both static and non static members of outer class directly. Static nested class 1) Without existing outer class object there may be a chance of existing static nested class object. That Is static nested class object is not associated with outer class object. 2) Inside static nested class we can declare static members. 3) Inside static nested class we can declare main() method and hence we can invoke static nested class directly from the command prompt. 4) From static nested class we can access only static members of outer class directly. ‘arious possible combinations of nested class & imerface: 1. class inside a class. = We can declare a class inside another class + Without existing one type of object, if there is no chance of existing another type of object, then we should go for clas inside a class class University { class Department { } ) Without existing University object, there is no chance of existing Department object. ie., Department object is always associated with University 2. interface fea class ‘We can declare interface inside a class. DURGASOFT, # 202.2% 19 joor HUDA Maitrivanam Ameerpet, Hyderabac ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com ‘500038, Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes class X { interface Y { ? ) Inside class if we required multiple implements of an interface and these implementations of relevant to a perticular class, then we should declare interface inside a class. class VehicleType { interface Vehicle { Public int getNoOfWheels(); } class Bus implements Vehicle { public int getNoofwheels() { return 6; } } class Auto implements Vehicle { public int getNoOfwheels() { return 3; ) interface inside a interface: ‘We can declare an interface inside another interface. interface Map { interface Entry { public Object getKey(); public Object getvalue() ; public Object getValue(Object new ); } ) Nested interfaces are always public, static whether we are declaring or not. Hence we can implements inner inteface directly with out implementing outer interface. interface outer { public void methodone(); interface Inner { public void methodtwo() ; ) ) class Test implements Outer.Inner { public void methodtwo() { 20 | DURGASOFT, #202,2" Floor HUDA Maitrvanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes system.out.println("Inner interface method") ; at public static void main(String args[]) { Test t=new Test (); t.methodtwo () 7 } } ‘Whenever we are implementing Outer interface , itis not required to implement Inner Interfaces. class Test implements outer ( public void methodone() { system.out.printIn("Outer interface method ") ; ) public static void main(String args[]) { Test t=new Test() ; t.methodone () ; , ) ie., Both Outer and Inner interfaces we can implement independently. 4.class inside a interface: ‘We can declare a class inside interface. Ifa class functionality is closely associated with the use interface then it is highly recommended to declare class inside interface Example: interface Emailserver { public void sendkmail (kmailDetails e) ; class EmailDetails { string from; String to; String subject; , } In the above example Emaildetalls functionality is required for EmallService and we are not using anyware else . Hence we can declare EmailDetalls class inside EmailService Interface . ‘We can also declare a class inside interface to provide default implementation for that interface. Example : interface Vehicle { public int getNoofwheels() ; 1 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Inner Classes class DefaultVehicle implements Vehicle { public int getNoofwheels() { return 3; } at , class Bus implements Vehicle { public int getNoofwheels() { return 6; , ) class Test { public static void main(String args[]) { Bus b=new Bus(); System.out.print1n (b.getNoofWheels()) ; Vehicle.DefaultVehicle d-new Vehicle.DefaultVehicle() ; system.out.print1n(d.getNoofWheels()) ; ¥ } In the above example DefaultVehicle in the default implementation of Vehicle interface ‘where as Bus customized implementation of Vehicle interface. The class which is declared inside interface is always static hence we can create object directly without having outer interface type object. Conclusions: 1. We can declare anything inside any thing with respect to classes and interfaces. 2. Nesting interfaces are always public, static whether we are declaring or not. 3. class which Is declared inside Interface Is always public,static whether we are declaring or not. 2a | BURGASOFT, #202,2" Floor HUDA Maitvanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com

You might also like