SlideShare a Scribd company logo
Compose by
Adil Mehmood
Adilm717@gmail.com
What is Inner classes
Top-Level (or Outer) Class
You can put a class inside an another class.
 A class that contains other classes is a TLC.
Classe that you can write inside another class. Common applications include
iterators and GUIs
Syantax:
class Outer{
class Inner{ }
}
note:
there is no top level static class in java unlike C#
there is only inner static class
Nested Class
Nested class:
• Class declared inside another class.
Two kinds of nested classes:
• Member class: class declared at the
member-level of a TLC.
• Local class: class declared inside a
method, constructor, or initializer block
Inner Class
Inner class(IC) refers to two special kinds of nested class:
• Non-static member class (member class with no staticmodifier).
• Local class inside a non-static member of a TLC.
Why called inner class?
• Because an object made from the class will containa reference to the
TLC.
• Use TLC.this.memberfrom inside inner class to access member of
TLC.
Restrictions:
• Inner class fields can be static, but then must also be final.
• No staticmethods or other inner classes (same for other members?)
• See language references for even more details
Handy way to think of inner
classes inside a TLC
At the member level:
- just like a variable or method.
- called member class.
At the statement level:
- just like a statement in a method
- called local class
At the expression level:
- just like an expression
- called anonymous class
Member Class (Member Level)
Rules
Structure:
public class OuterClass{
tlc_members
public class InnerClass{
mc_members
}
}
When to use?
• The inner class generates objects used specifically by TLC.
• The inner class is associated with, or “connected to,” the TLC
How does visibility work?
• The inner class can be public, private, protected,
or package.
• Instances of the inner class type have
access to all members of the outer class
(including private and static members).
Some restrictions:
• Cannot have same name as TLC or package (not
that you would want to!).
• Cannot contain static members; can have static
finalfields (constants).
How do you use a member
class?
OuterClass oref = new OuterClass();
OuterClass.InnerClass iref = oref.new
InnerClass()
iref.doSomething();
new OuterClass().new InnerClass();
• Not valid:
InnerClass iref = new InnerClass();
iref.doSomething();
Internal references with this:
• Inside inner class, the this refers to current
instance of the inner class.
• To get to current instance of TLC, save the
TLC’s this as field in the TLC or
simply use TLC.this.
public class MemberClass {
public static void main(String[] args) {
// one way:
OC a = new OC();
OC.IC b = a.new IC();
b.print(); // outputs 3
// another way:
new OC().new IC().print(); // outputs 3
}
}
class OC {
private int x = 1;
public class IC {
private int y = 2;
public void print() {System.out.println(x+y);}
}
}
Local Classes (Statement Level)
Local class location:
• Statement level declaration.
• Usually written in methods. See also constructors
and initializers.
Scope:
• Local to block.
• Can access all members of the TLC.
• Actually, things can get confusing here!
- An object of local class might persist after
method ends.
- Java does have rules for dealing with the matter
More restrictions:
• Cannot be used outside of block.
• No modifiers.
• Enclosing block’s variables must be finalfor local
class to access.
• No static, but can have static final(constants).
• Terminate with a semicolon! The class is
effectively an expression statement.
• Cannot have same name of TLC
public class LocalClass {
public static void main(String[] args) {
new OC().print();
}
}
class OC {
public void print() {
final String s = "test: ";
class Point {
private int x;
private int y;
public Point(int x,int y) { this.x=x; this.y=y; }
public String toString() { return s+"("+x+","+y+")"; }
};
System.out.println(new Point(1,2));
} // method print
} //
Anonymous Class
Location and structure:
• Defined and created at expressionlevel.
• So, has no name and no modifiers.
Syntax:
new classname( argumentlist) { classbody}
new interfacename( argumentlist) { classbody}
Adapter class:
• Adapter class defines code that another object invokes.
• Common in GUIs and iterators.
Some restrictions:
• No modifiers.
• No static, but can have static final(constants).
• No constructors, but can use initializers for samepurpose! (See Section 1.2.)
When to use?
• Class has very short body.
• Only one instance of class needed.
• Class used right after defined; no need to create new class
In example below, we print a Pointagain. But, we cannot say new Point, because we
have not defined a Pointclass. Instead, I use a placeholder, class Object. You will often
find yourself using interface names instead.
public class AnonymousClass {
public static void main(String[] args) {
new OC().print();
}
}
class OC {
public void print() {
final String s = "test: ";
System.out.println(new Object() {
private int x=1;
private int y=2;
public String toString() { return s+"("+x+","+y+")"; }
} );
}
Instantiating an Inner class
Instantiating an Inner Class from within Outer
classes
code:
class Outer{!
private int x = 7;!
public void makeInner(){!
Inner x = new Inner();!
x.seeOuter();!
}!
class Inner{!
public void seeOuter(){!
System.out.println(x);!
}!
}!
}!
5
Creating an Inner Class from
Outside of the Outer class
You have to have instance of the
Outer-class
–  Outer outer = new Outer();
  After that, you create the Inner object
–  Outer.Inner inner = outer.new Inner() ;
• One Liner:
–  Outer.Inner inner = (new Outer()).new
Inner() ;
Method-local Inner Classes
Class inside a method
•  Can be instantiated only within the
method (below the class)
•  Can use Outer classes private
members
•  Cannot use methods variables!!
–  Unless the variable is final...
class Outer{!
private int x = 7;!
public void method(){!
final String y = "hi!";!
String z = "hi!";!
class Inner{!
public void seeOuter(){!
System.out.println(x); // works!!
System.out.println(y); // works!
//System.out.println(z); // doesn't work!
}!
}!
Inner object = new Inner();!
object.seeOuter();!
}!
}!

More Related Content

PPTX
Java abstract class & abstract methods
PPTX
Interface in java
PPTX
Understanding java streams
PPT
Method overriding
PDF
Java Course 8: I/O, Files and Streams
PDF
Methods in Java
PPTX
Java class,object,method introduction
PPTX
Java constructors
Java abstract class & abstract methods
Interface in java
Understanding java streams
Method overriding
Java Course 8: I/O, Files and Streams
Methods in Java
Java class,object,method introduction
Java constructors

What's hot (20)

PPTX
Constructor in java
PPTX
Java features
PPTX
Core java complete ppt(note)
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PPT
Abstract class in java
PPTX
Super keyword in java
PPTX
Java program structure
PPTX
Control flow statements in java
PPTX
Introduction to java
PPTX
Strings in Java
PPTX
Methods in java
PPTX
L21 io streams
PPT
9. Input Output in java
PPTX
Multithreading in java
PPTX
Inheritance in JAVA PPT
PPTX
Java package
PPTX
Inter Thread Communicationn.pptx
PPTX
PPTX
Static Members-Java.pptx
Constructor in java
Java features
Core java complete ppt(note)
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Abstract class in java
Super keyword in java
Java program structure
Control flow statements in java
Introduction to java
Strings in Java
Methods in java
L21 io streams
9. Input Output in java
Multithreading in java
Inheritance in JAVA PPT
Java package
Inter Thread Communicationn.pptx
Static Members-Java.pptx
Ad

Viewers also liked (20)

PDF
Java Inner Classes
PDF
Classes and Nested Classes in Java
PPTX
Inner classes
DOCX
Nested classes in java
PPT
Inner classes9 cm604.28
PPTX
Inner class
PPT
Character stream classes .52
PPT
Byte stream classes.49
PDF
PPT
Various io stream classes .47
PPT
Java: Objects and Object References
PPT
Collections Framework
PPT
JAVA Variables and Operators
PPT
JAVA OOP
PPT
L5 classes, objects, nested and inner class
PPTX
Java Input Output (java.io.*)
PPT
Object and Classes in Java
PPTX
Inner Classes & Multi Threading in JAVA
PPTX
Java- Nested Classes
PPT
Jsp/Servlet
Java Inner Classes
Classes and Nested Classes in Java
Inner classes
Nested classes in java
Inner classes9 cm604.28
Inner class
Character stream classes .52
Byte stream classes.49
Various io stream classes .47
Java: Objects and Object References
Collections Framework
JAVA Variables and Operators
JAVA OOP
L5 classes, objects, nested and inner class
Java Input Output (java.io.*)
Object and Classes in Java
Inner Classes & Multi Threading in JAVA
Java- Nested Classes
Jsp/Servlet
Ad

Similar to Inner classes ,annoumous and outer classes in java (20)

PPT
A1771937735_21789_14_2018__16_ Nested Classes.ppt
DOCX
Nested class in java
PPTX
Javasession8
PPTX
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
PPTX
Java Nested class Concept
PPTX
Nested classes in java
PPTX
Nested class
PDF
Inner Classes in Java
PPTX
Java Programming inner and Nested classes.pptx
PPTX
Java Nested classes, static class and methods, nested blocks_Inner_Classes.pptx
PPTX
Object oriented programming CLASSES-AND-OBJECTS.pptx
PPTX
Java Inner Class
PDF
Java Inner Classes
PPTX
Java basics
PPTX
Inner class
PPTX
types of classes in java
PDF
Classes in Java great learning.pdf
PPTX
Inner classes in java
PPT
Inner Classes
PDF
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
A1771937735_21789_14_2018__16_ Nested Classes.ppt
Nested class in java
Javasession8
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
Java Nested class Concept
Nested classes in java
Nested class
Inner Classes in Java
Java Programming inner and Nested classes.pptx
Java Nested classes, static class and methods, nested blocks_Inner_Classes.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptx
Java Inner Class
Java Inner Classes
Java basics
Inner class
types of classes in java
Classes in Java great learning.pdf
Inner classes in java
Inner Classes
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf

More from Adil Mehmoood (19)

PPTX
Docker + Node "hello world" Application
PPT
Java database connectivity with MYSQL
PDF
What is feasibility study and what is contracts and its type
PPTX
Exception handling in java
DOC
Project Engineer and Deputy project manger
PPT
Swing and AWT in java
PPT
Software Engineering 2 lecture slide
PPT
Expert system
PPT
Sliding window and error control
PPTX
Proposal defence format
PPT
Shading and two type of shading flat shading and gauraud shading with coding ...
PPT
Computer vesion
PPT
System quality attributes
DOC
Graph Clustering and cluster
PPT
Token ring 802.5
PPT
diseases caused by computer
PPT
Diseases caused by Computer
PPT
What is Resume ,purpose and objective of resume and type of resume
PPT
Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)
Docker + Node "hello world" Application
Java database connectivity with MYSQL
What is feasibility study and what is contracts and its type
Exception handling in java
Project Engineer and Deputy project manger
Swing and AWT in java
Software Engineering 2 lecture slide
Expert system
Sliding window and error control
Proposal defence format
Shading and two type of shading flat shading and gauraud shading with coding ...
Computer vesion
System quality attributes
Graph Clustering and cluster
Token ring 802.5
diseases caused by computer
Diseases caused by Computer
What is Resume ,purpose and objective of resume and type of resume
Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)

Recently uploaded (20)

PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
PPTX
Congenital Hypothyroidism pptx
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
English Language Teaching from Post-.pdf
PDF
Sunset Boulevard Student Revision Booklet
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
How to Manage Global Discount in Odoo 18 POS
PDF
Landforms and landscapes data surprise preview
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
PDF
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PDF
High Ground Student Revision Booklet Preview
PDF
LDMMIA Reiki Yoga Workshop 15 MidTerm Review
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Open Quiz Monsoon Mind Game Prelims.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Renaissance Architecture: A Journey from Faith to Humanism
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
Congenital Hypothyroidism pptx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
English Language Teaching from Post-.pdf
Sunset Boulevard Student Revision Booklet
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
How to Manage Global Discount in Odoo 18 POS
Landforms and landscapes data surprise preview
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
How to Manage Starshipit in Odoo 18 - Odoo Slides
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
High Ground Student Revision Booklet Preview
LDMMIA Reiki Yoga Workshop 15 MidTerm Review
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table

Inner classes ,annoumous and outer classes in java

  • 2. What is Inner classes Top-Level (or Outer) Class You can put a class inside an another class.  A class that contains other classes is a TLC. Classe that you can write inside another class. Common applications include iterators and GUIs Syantax: class Outer{ class Inner{ } } note: there is no top level static class in java unlike C# there is only inner static class
  • 3. Nested Class Nested class: • Class declared inside another class. Two kinds of nested classes: • Member class: class declared at the member-level of a TLC. • Local class: class declared inside a method, constructor, or initializer block
  • 4. Inner Class Inner class(IC) refers to two special kinds of nested class: • Non-static member class (member class with no staticmodifier). • Local class inside a non-static member of a TLC. Why called inner class? • Because an object made from the class will containa reference to the TLC. • Use TLC.this.memberfrom inside inner class to access member of TLC. Restrictions: • Inner class fields can be static, but then must also be final. • No staticmethods or other inner classes (same for other members?) • See language references for even more details
  • 5. Handy way to think of inner classes inside a TLC At the member level: - just like a variable or method. - called member class. At the statement level: - just like a statement in a method - called local class At the expression level: - just like an expression - called anonymous class
  • 6. Member Class (Member Level) Rules Structure: public class OuterClass{ tlc_members public class InnerClass{ mc_members } } When to use? • The inner class generates objects used specifically by TLC. • The inner class is associated with, or “connected to,” the TLC
  • 7. How does visibility work? • The inner class can be public, private, protected, or package. • Instances of the inner class type have access to all members of the outer class (including private and static members). Some restrictions: • Cannot have same name as TLC or package (not that you would want to!). • Cannot contain static members; can have static finalfields (constants).
  • 8. How do you use a member class? OuterClass oref = new OuterClass(); OuterClass.InnerClass iref = oref.new InnerClass() iref.doSomething(); new OuterClass().new InnerClass(); • Not valid: InnerClass iref = new InnerClass(); iref.doSomething();
  • 9. Internal references with this: • Inside inner class, the this refers to current instance of the inner class. • To get to current instance of TLC, save the TLC’s this as field in the TLC or simply use TLC.this.
  • 10. public class MemberClass { public static void main(String[] args) { // one way: OC a = new OC(); OC.IC b = a.new IC(); b.print(); // outputs 3 // another way: new OC().new IC().print(); // outputs 3 } } class OC { private int x = 1; public class IC { private int y = 2; public void print() {System.out.println(x+y);} } }
  • 11. Local Classes (Statement Level) Local class location: • Statement level declaration. • Usually written in methods. See also constructors and initializers. Scope: • Local to block. • Can access all members of the TLC. • Actually, things can get confusing here! - An object of local class might persist after method ends. - Java does have rules for dealing with the matter
  • 12. More restrictions: • Cannot be used outside of block. • No modifiers. • Enclosing block’s variables must be finalfor local class to access. • No static, but can have static final(constants). • Terminate with a semicolon! The class is effectively an expression statement. • Cannot have same name of TLC
  • 13. public class LocalClass { public static void main(String[] args) { new OC().print(); } } class OC { public void print() { final String s = "test: "; class Point { private int x; private int y; public Point(int x,int y) { this.x=x; this.y=y; } public String toString() { return s+"("+x+","+y+")"; } }; System.out.println(new Point(1,2)); } // method print } //
  • 14. Anonymous Class Location and structure: • Defined and created at expressionlevel. • So, has no name and no modifiers. Syntax: new classname( argumentlist) { classbody} new interfacename( argumentlist) { classbody} Adapter class: • Adapter class defines code that another object invokes. • Common in GUIs and iterators. Some restrictions: • No modifiers. • No static, but can have static final(constants). • No constructors, but can use initializers for samepurpose! (See Section 1.2.) When to use? • Class has very short body. • Only one instance of class needed. • Class used right after defined; no need to create new class
  • 15. In example below, we print a Pointagain. But, we cannot say new Point, because we have not defined a Pointclass. Instead, I use a placeholder, class Object. You will often find yourself using interface names instead. public class AnonymousClass { public static void main(String[] args) { new OC().print(); } } class OC { public void print() { final String s = "test: "; System.out.println(new Object() { private int x=1; private int y=2; public String toString() { return s+"("+x+","+y+")"; } } ); }
  • 16. Instantiating an Inner class Instantiating an Inner Class from within Outer classes code: class Outer{! private int x = 7;! public void makeInner(){! Inner x = new Inner();! x.seeOuter();! }! class Inner{! public void seeOuter(){! System.out.println(x);! }! }! }! 5
  • 17. Creating an Inner Class from Outside of the Outer class You have to have instance of the Outer-class –  Outer outer = new Outer();   After that, you create the Inner object –  Outer.Inner inner = outer.new Inner() ; • One Liner: –  Outer.Inner inner = (new Outer()).new Inner() ;
  • 18. Method-local Inner Classes Class inside a method •  Can be instantiated only within the method (below the class) •  Can use Outer classes private members •  Cannot use methods variables!! –  Unless the variable is final...
  • 19. class Outer{! private int x = 7;! public void method(){! final String y = "hi!";! String z = "hi!";! class Inner{! public void seeOuter(){! System.out.println(x); // works!! System.out.println(y); // works! //System.out.println(z); // doesn't work! }! }! Inner object = new Inner();! object.seeOuter();! }! }!