SlideShare a Scribd company logo
1 of 13
Download to read offline
Inner Classes
 Jussi Pohjolainen




                     1
Regular Inner Class
class Outer{!
  class Inner{ }!
}!
javac Outer.java!
=>!
Outer.class!
Outer$Inner.class!

                           2
Running the inner-class
•  You can't access the Inner class in a
   usual way
  –  java Outer$Inner
  –  because regular Inner-class cannot
     contain main-method. It cannot contain
     any static content!



                                         3
Private members
•  Inner class can have access to Outer
   classes private members
class Outer {!
     private int x = 7;!
     class Inner {!
          public void seeOuter() {!
             System.out.println(x);!
          }!
     }!
}!                                     4
Instantiating an Inner class
•  To instantiate: You must have an instance of the outer
   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()

    Class Class          Object   new Object

•  One Liner:
  –  Outer.Inner inner = (new Outer()).new Inner()
                                             6
Referencing Inner / Outer
    class from Inner class
class Outer{
   class Inner{
      public void seeOuter(){
        System.out.println(this);
        System.out.println(Outer.this);
      }
   }
}                                     7
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...

                                         8
Example
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();!
    }!
}!
                                                    9
Anonymous Inner Classes
    class Popcorn {!
        public void pop() {!
            System.out.println("popcorn");!
        }!
    }!                                  Subclass
    !                                      of
    class Food {!                       Popcorn!
        Popcorn p = new Popcorn() {!
            public void pop() {!
superclass!    System.out.println("subclass Popcorn!");!
            }!
        };!       Notice the semicolon!
    !
    }!
                                                   10
Anonymous Inner classes
          (Interface)
interface Cookable {!
   public void cook();!
}!
!
class Food {!               Implementation of the Interface
   Cookable p = new Cookable() {!
      public void cook() {!
         System.out.println("Cook
         implementer");!
      }!
   };!
}!
                                               11
Argument-Defined Anonymous
        Inner Class
class MyClass{!
   void go(){!
      Bar b = new Bar();!
      b.doStuff(new Foo() {!
         public void foof() {!
            System.out.println("foofy");!
         }!
      });!
   }!
}!
!                                        12
Static Nested Classes
•  Static member of the enclosing class.
•  class BigOuter{
  –  static class Nested { }
•  }
•  Does not have access to the instance
   variables!
•  BigOuter.Nested n = new
   BigOuter.Nested()
                                     13

More Related Content

What's hot

Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
Ravi_Kant_Sahu
 
Inner classes9 cm604.28
Inner classes9 cm604.28Inner classes9 cm604.28
Inner classes9 cm604.28
myrajendra
 
Inner Classes
Inner ClassesInner Classes
Inner Classes
parag
 
[圣思园][Java SE]Inner class
[圣思园][Java SE]Inner class[圣思园][Java SE]Inner class
[圣思园][Java SE]Inner class
ArBing Xie
 

What's hot (18)

L5 classes, objects, nested and inner class
L5 classes, objects, nested and inner classL5 classes, objects, nested and inner class
L5 classes, objects, nested and inner class
 
Module 11 : Inheritance
Module 11 : InheritanceModule 11 : Inheritance
Module 11 : Inheritance
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Inner classes9 cm604.28
Inner classes9 cm604.28Inner classes9 cm604.28
Inner classes9 cm604.28
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Inner classes
Inner classesInner classes
Inner classes
 
Inner Classes
Inner ClassesInner Classes
Inner Classes
 
Java Inner Classes
Java Inner ClassesJava Inner Classes
Java Inner Classes
 
Inner Classes in Java
Inner Classes in JavaInner Classes in Java
Inner Classes in Java
 
Pj01 x-classes and objects
Pj01 x-classes and objectsPj01 x-classes and objects
Pj01 x-classes and objects
 
Unit 5 java-awt (1)
Unit 5 java-awt (1)Unit 5 java-awt (1)
Unit 5 java-awt (1)
 
[圣思园][Java SE]Inner class
[圣思园][Java SE]Inner class[圣思园][Java SE]Inner class
[圣思园][Java SE]Inner class
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
class c++
class c++class c++
class c++
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Classes
ClassesClasses
Classes
 
Write First C++ class
Write First C++ classWrite First C++ class
Write First C++ class
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 

Viewers also liked

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
myrajendra
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
myrajendra
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
myrajendra
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
yoavwix
 

Viewers also liked (20)

Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
 
Files in java
Files in javaFiles in java
Files in java
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Event handling
Event handlingEvent handling
Event handling
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
 
Java Basics
Java BasicsJava Basics
Java Basics
 
The visual interface is now your brand
The visual interface is now your brandThe visual interface is now your brand
The visual interface is now your brand
 

Similar to Java Inner Classes

Java Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptxJava Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptx
AkashJha84
 
LECTURE 7 REVIEW, EXCEPTIONS, IO.pdf
LECTURE 7 REVIEW, EXCEPTIONS, IO.pdfLECTURE 7 REVIEW, EXCEPTIONS, IO.pdf
LECTURE 7 REVIEW, EXCEPTIONS, IO.pdf
ShashikantSathe3
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
saryu2011
 

Similar to Java Inner Classes (20)

Java Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptxJava Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptx
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
 
A1771937735_21789_14_2018__16_ Nested Classes.ppt
A1771937735_21789_14_2018__16_ Nested Classes.pptA1771937735_21789_14_2018__16_ Nested Classes.ppt
A1771937735_21789_14_2018__16_ Nested Classes.ppt
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
LECTURE 7 REVIEW, EXCEPTIONS, IO.pdf
LECTURE 7 REVIEW, EXCEPTIONS, IO.pdfLECTURE 7 REVIEW, EXCEPTIONS, IO.pdf
LECTURE 7 REVIEW, EXCEPTIONS, IO.pdf
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 
core java
core javacore java
core java
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java
JavaJava
Java
 
Inheritance
InheritanceInheritance
Inheritance
 
Session 21 - Inner Classes
Session 21 - Inner ClassesSession 21 - Inner Classes
Session 21 - Inner Classes
 
Anonymous classes2
Anonymous classes2Anonymous classes2
Anonymous classes2
 
Java OO Revisited
Java OO RevisitedJava OO Revisited
Java OO Revisited
 
Turbinando o compilador do Java 8
Turbinando o compilador do Java 8Turbinando o compilador do Java 8
Turbinando o compilador do Java 8
 
Logic and Coding of Java Interfaces & Swing Applications
Logic and Coding of Java Interfaces & Swing ApplicationsLogic and Coding of Java Interfaces & Swing Applications
Logic and Coding of Java Interfaces & Swing Applications
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
 
inheritance
inheritanceinheritance
inheritance
 
Inner Classes
Inner Classes Inner Classes
Inner Classes
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 

More from Jussi Pohjolainen

Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
Jussi Pohjolainen
 

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Java Inner Classes

  • 1. Inner Classes Jussi Pohjolainen 1
  • 2. Regular Inner Class class Outer{! class Inner{ }! }! javac Outer.java! =>! Outer.class! Outer$Inner.class! 2
  • 3. Running the inner-class •  You can't access the Inner class in a usual way –  java Outer$Inner –  because regular Inner-class cannot contain main-method. It cannot contain any static content! 3
  • 4. Private members •  Inner class can have access to Outer classes private members class Outer {! private int x = 7;! class Inner {! public void seeOuter() {! System.out.println(x);! }! }! }! 4
  • 5. Instantiating an Inner class •  To instantiate: You must have an instance of the outer 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 }!
  • 6. 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() Class Class Object new Object •  One Liner: –  Outer.Inner inner = (new Outer()).new Inner() 6
  • 7. Referencing Inner / Outer class from Inner class class Outer{ class Inner{ public void seeOuter(){ System.out.println(this); System.out.println(Outer.this); } } } 7
  • 8. 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... 8
  • 9. Example 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();! }! }! 9
  • 10. Anonymous Inner Classes class Popcorn {! public void pop() {! System.out.println("popcorn");! }! }! Subclass ! of class Food {! Popcorn! Popcorn p = new Popcorn() {! public void pop() {! superclass! System.out.println("subclass Popcorn!");! }! };! Notice the semicolon! ! }! 10
  • 11. Anonymous Inner classes (Interface) interface Cookable {! public void cook();! }! ! class Food {! Implementation of the Interface Cookable p = new Cookable() {! public void cook() {! System.out.println("Cook implementer");! }! };! }! 11
  • 12. Argument-Defined Anonymous Inner Class class MyClass{! void go(){! Bar b = new Bar();! b.doStuff(new Foo() {! public void foof() {! System.out.println("foofy");! }! });! }! }! ! 12
  • 13. Static Nested Classes •  Static member of the enclosing class. •  class BigOuter{ –  static class Nested { } •  } •  Does not have access to the instance variables! •  BigOuter.Nested n = new BigOuter.Nested() 13