Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013

Similar documents
Declarations and Access Control SCJP tips

Packages Inner Classes

Java: introduction to object-oriented features

Programming overview

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

Object Orientation Fourth Story. Bok, Jong Soon

Overview. Elements of Programming Languages. Objects. Self-Reference

CMSC 132: Object-Oriented Programming II

C08: Inheritance and Polymorphism

Chapter 13. Interfaces and Inner Classes

1 Shyam sir JAVA Notes

ENCAPSULATION. private, public, scope and visibility rules. packages and package level access.

Goal. Generic Programming and Inner classes. Minor rewrite of linear search. Obvious linear search code. Intuitive idea of generic linear search

C30b: Inner Class, Anonymous Class, and Lambda Expression

CMSC 132: Object-Oriented Programming II

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Class, Variable, Constructor, Object, Method Questions

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

CS 231 Data Structures and Algorithms, Fall 2016

Overview. Elements of Programming Languages. Objects. Self-Reference

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

CPS 506 Comparative Programming Languages. Programming Language

Lecture 10 Declarations and Scope

Introduction to Programming Using Java (98-388)

enum Types 1 1 The keyword enum is a shorthand for enumeration. Zheng-Liang Lu Java Programming 267 / 287

CS61B Lecture #13: Packages, Access, Etc.

C++ Inheritance and Encapsulation

Chapter 6 Introduction to Defining Classes

Java Object Oriented Design. CSC207 Fall 2014

Another IS-A Relationship

Topic 6: Inner Classes

Array. Prepared By - Rifat Shahriyar

Java Loose Ends. 11 December 2017 OSU CSE 1

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

The Essence of OOP using Java, Nested Top-Level Classes. Preface

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Fundamentals of Object Oriented Programming

*An nested class is a class that is defined inside another class.

STRUCTURING OF PROGRAM


Software Design and Analysis for Engineers

CS61B Lecture #13: Packages, Access, Etc.

Last name:... First name:... Department (if not D-INFK):...

Lecture 02, Fall 2018 Friday September 7

Timing for Interfaces and Abstract Classes

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Binghamton University. CS-140 Fall Dynamic Types

Programming Language Concepts: Lecture 2

Protection Levels and Constructors The 'const' Keyword

CH. 2 OBJECT-ORIENTED PROGRAMMING

ECS 140A Midterm 2 November 19, Name (Last, First):, Sign your name:

Semantic Analysis. Lecture 9. February 7, 2018

Inheritance and Polymorphism. CS180 Fall 2007

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

What about Object-Oriented Languages?

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Extending Classes (contd.) (Chapter 15) Questions:

Conformance. Object-Oriented Programming Spring 2015

The Notion of a Class and Some Other Key Ideas (contd.) Questions:

Inheritance, and Polymorphism.

Building custom components IAT351

Compaq Interview Questions And Answers

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Inheritance. Transitivity

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

CS260 Intro to Java & Android 03.Java Language Basics

COMP 250: Java Object Oriented Programming

Chapter 17: Nested Classes

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

The Decaf Language. 1 Lexical considerations

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

C10: Garbage Collection and Constructors

Lecture Notes on Programming Languages

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Chapter 4 Defining Classes I

Design Patterns: State, Bridge, Visitor

Programming Languages and Techniques (CIS120)

Vendor: Oracle. Exam Code: 1Z Exam Name: Java Certified Programmer. Version: Demo

What does it mean by information hiding? What are the advantages of it? {5 Marks}

Interfaces. An interface forms a contract between the object and the outside world.

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics

CITS2210 Object-Oriented Programming. Topic 10. Java: Nested and Inner Classes

QUIZ. What is wrong with this code that uses default arguments?

Supporting Class / C++ Lecture Notes

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

CS121/IS223. Object Reference Variables. Dr Olly Gotel

What is Inheritance?

Semantic Analysis and Type Checking

class objects instances Fields Constructors Methods static

A Short Summary of Javali

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Data Abstraction. Hwansoo Han

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

JAVA Programming Language Homework I - OO concept

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

JAVA OBJECT-ORIENTED PROGRAMMING

Transcription:

Nested Classes in Java Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013 1

In This Tutorial Explanation of the nested class concept. Access modifiers and nested classes. The types of nested classes in Java. Inheritance and inner classes. Nested classes in the JVM. Limits and caveats 2

The Concept Like C++, Java supports defining classes inside other classes. The general term for these classes is nested classes. Classes which are not defined inside other classes are called top-level classes. In Java, there are 4 types of nested classes. Nested classes are used extensively in Java. 3

Access Control Reminder: in Java there are 4 access control modifiers. Here s a more accurate table of their effects: Modifier public protected private default Accessible from (in addition to defining class) Any class of any package Subclasses + any class of the same package Only classes that share the same top-level class as the defining class Any class of the same package What does this mean about nested classes? 4

Type 1 Static Nested Classes Defined as member classes, with the static modifier. Most similar to nested classes in C++. Helps in encapsulation for example, if B is useful only to A. A static nested class can have any visibility, just like any other member. Cannot access non-static members of enclosing class. class A {... static class B {...... 5

Inner Classes Nested classes which are not static are called inner classes. There are 3 kinds of inner classes: non-static member class, a.k.a. (regular) inner class local class anonymous class An instance of an inner classes is associated with an instance of the enclosing class. Consequentially, inner classes can access nonstatic members of the enclosing class. 6

More on Inner Classes Instances of enclosing / nested classes do not contain each other they are only associated with each other. An instance of an enclosing class may be associated with multiple instances of inner classes. An instance of an inner class is associated with exactly one instance of the enclosing class. 7

Type 2 Non-Static Member Classes Defined as member classes, without the static modifier. An instance of B is always associated with an instance of A. A.B can have any visibility. Created with qualified new A a = new A(); A.B ab = a.new B(); class A {... class B {...... // ab is associated with a 8

Access to enclosing class If B is an inner class of A, it may access the associated A instance s this pointer via the qualified A.this This access is only available for non static nested classes (why?). class A { void foo() { System.out.println( A ); class B { void foo() { System.out.println( B ); void bar() { A.this.foo(); //prints A 9

Type 3 Local Classes Defined inside a method, and only visible from the point it is declared to the end of the method. If defined inside a non-static method, is considered an inner class and has access to nonstatic members otherwise, behaves more like static nested class. Can access parameters as well as local variables declared in the same method before the class is declared, but only as long as they are marked final (why?). 10

Local Classes - Example class Outer { private int x; void f(final int z) { final int y = 4; class Inner { void inc() { x += z + y; // Legal y and z are final Inner i = new Inner(); static void g() { Inner i = new Inner(); // Illegal class declaration // must appear first class Inner { // Legal to use the same name void inc() { x++; // Illegal cannot access non-static field x 11

Type 4 Anonymous Classes Local classes are useful when you need to use some local variable inside it. However, typically only one instance of these classes are needed per method invocation. Anonymous classes are also created inside the body of a method, however Defining the class also defines an instance of it No more instances can be defined from that class Probably the most complicated of the nested class types, and probably the most useful. 12

Anonymous Classes - Syntax new <parent class / interface>(<arguments>) { <anonymous class body> Simple example: interface A { void g(); class B { void f() { A a = new A() { void g() { ; a.g(); 13

Anonymous Classes & Constructors Anonymous classes cannot have constructors* (they don t even have a name). Constructors of a parent class can be invoked using the argument list. class A { public A(int x) {... void g() {... class B { A f() { return (new A(3){);id g() {...).g(); * They can have instance initializers, though. Outside of our scope. 14

Nested Class Types Summary Type Inner (associated with outer instance) Definition point Static nested class No As a member of another class. Non-static member class (regular inner class) Local class Anonymous class Yes Yes (if defined in non-static method) Yes (if defined in non-static method) As a member of another class. Inside a method. As an expression (since defining it also returns the instance). Visibility Depends on access modifier. Depends on access modifier. From the point it is defined to the end of the method. None. 15

Inheriting from inner classes 1/2 It s possible to inherit from an inner class, but only as long as the inheriting class can be associated with a subtype of the original outer class. Example of the legal scenarios: class BaseOuter { class BaseInner { // Legal because BaseOuter is a subtype of BaseOuter: class BaseInner2 extends BaseInner { class DerivedOut extends BaseOuter { // Legal because DerivedOuter is a subtype of BaseOuter: class DerivedInner extends BaseInner { 16

Inheriting from inner classes 2/2 What would happen without this limitation? class Outer { int x; class Inner { void f() { x++; class Derived extends Outer.Inner { void somemethod() { new Derived().f(); // What will happen? 17

Nested Classes and the JVM There is no concept of nested classes in bytecode or in the JVM. The compiler generates a separate.class file for each class. Since access modifiers are enforced in the JVM, the compiler sometimes has to work hard to split nested classes into independent classes. public class Outer { class Inner { > javac Outer.java > ls Outer.java Outer.class Outer$Inner.class 18

Inner Classes and the JVM public class Outer { class Inner { Inner actually compiles to something like: class Outer$Inner { Outer $this; Inner(Outer $this) { this.$this = $this; Likewise, any outer local variables used are passed in the constructor, which is why only final locals are permitted (what would happen otherwise?) 19

Some Limitations of Nested Classes Nested interfaces are always implicitly static. Inner classes may not declare static members (with the exception of compile-time constant fields). 20

Blocks in Java? So, how would you create an equivalent to a SmallTalk block? interface Block { Object value(); Object value(object o1); Object value(object o1, Object o2); void foo(block ablock) { System.out.println(aBlock.value()); void bar() { What s missing? final int v = 42; foo(new Block() { @Override Object value() { return v; ); 21

Blocks in Java (2) abstract class Block { static class NotImplemented extends RuntimeException { Object value() { throw new NotImplemented(); Object value(object o1) { throw new NotImplemented(); Object value(object o1, Object o2) { throw new void bar() { final int v = 42; foo(new Block() { @Override Object value() { return v; ); Remember, Squeak s blocks are instances of a class too (BlockClosure) 22

More Information Sun s official tutorial at http://docs.oracle.com/javase/tutorial/java/ja vaoo/nested.html For the brave the Java Language Specification at http://docs.oracle.com/javase/specs/jls/se7/h tml/jls-8.html 23