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

Similar documents
Topic 6: Inner Classes

C30b: Inner Class, Anonymous Class, and Lambda Expression

Another IS-A Relationship

Packages Inner Classes

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

Timing for Interfaces and Abstract Classes

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

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

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

Interfaces (1/2) An interface forms a contract between the object and the outside world.

2IP15 Programming Methods

Swing: Building GUIs in Java

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

Swing: Building GUIs in Java

CS : Data Structures Michael Schatz. Sept Lecture 5: Iterators

A final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited.

List ADT. Announcements. The List interface. Implementing the List ADT

Programming Language Concepts: Lecture 6

Subtype Polymorphism

User Interface Programming OOP/Java Primer. Step 4 Some Final Checkups

Builder pattern. A creational pattern

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

Exercise. Zheng-Liang Lu Java Programming 273 / 324

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

CS 251 Intermediate Programming More on classes

Programming overview

Programming Languages and Techniques (CIS120)

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Chapter 4. Defining Classes I

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

Declarations and Access Control SCJP tips

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Linked List Nodes (reminder)

Exercise (Revisited)

Nested Loops. A loop can be nested inside another loop.

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

C08: Inheritance and Polymorphism

Example: Monte Carlo Simulation 1

Reflection. Based on

Array. Prepared By - Rifat Shahriyar

Introduction to Programming Using Java (98-388)

Repetition and Loop Statements Chapter 5

C09: Interface, and Abstract Class and Method

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Inner Classes. CMSC 433 Programming Language Technologies and Paradigms Spring Example: The Queue Class. Example: The Queue Class (cont d)

Java Strings Java, winter semester

Collections and Iterators. Collections

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Object Oriented Software Design

Programming Languages and Techniques (CIS120)

An Activation Record for Simple Subprograms. Activation Record for a Language with Stack-Dynamic Local Variables

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CP122 CS I. Iteration

Chapter 4: Loops and Files

Object-Oriented Programming in Java

Chapter 4: Loops and Files

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

CMSC 132: Object-Oriented Programming II

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Java Exceptions Java, winter semester

About this exam review

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Programming Languages and Techniques (CIS120)

Computational Expression

Control Flow Statements

Programming Languages and Techniques (CIS120e)

Exceptions, Case Study-Exception handling in C++.

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Java Certification Model Question & Answer

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

Programming by Delegation

STUDENT LESSON A12 Iterations

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Introduction to Object-Oriented Programming

Short Notes of CS201

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Chapter 13. Interfaces and Inner Classes

Chapter 17: Nested Classes

CS201 - Introduction to Programming Glossary By

CS1150 Principles of Computer Science Loops (Part II)

Principles of Object Oriented Programming. Lecture 4

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Encapsulation in Java

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it

Understanding class definitions

ITI Introduction to Computing II

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Object Orientation Fourth Story. Bok, Jong Soon

The data in the table are arranged into 12 rows and 12 columns. The process of printing them out can be expressed in a pseudocode algorithm as

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

G Programming Languages - Fall 2012

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

Oracle 1Z Java Certified Programmer. Download Full Version :

CHAPTER 7 OBJECTS AND CLASSES

Transcription:

CITS2210 Object-Oriented Programming Topic 10 Java: Nested and Inner Classes Summary: Nested and inner classes allow classes do be defined within other classes, and even within bodies of methods. They enable certain styles of programming that are awkward otherwise. 1

What are nested and inner classes? A nested class is a class defined inside another class. public class OuterClass { class NestedClass { Nested class declarations can appear in classes and interfaces along with the more standard variable declarations and method declarations. Like other declarations, they can have modifiers like public, static, etc. A non-static nested class is called an inner class. You can always write separate classes instead of using nested classes, but they are still useful for the following reasons. They allow helper classes to be logically grouped with a main class. They allow improved encapsulation since nested classes can access private variables, and can be private themselves. They allow code to be better organized, with related code appearing in one place. 2

Static nested classes Static nested classes are attached to the outer class. They can only access static variables and methods from the outerclass directly. As such, static nested classes can usually be easily moved to become top-level classes the nesting is only used for organization. Static nested classes are can be accessed via the outer class, just like static methods and class variables (assuming that they are not private). public class Outer { public static class StaticNested { Outer.StaticNested nested = new Outer.StaticNested(); 3

Inner classes Inner classes are attached to a particular instance of the outer class. So, each instance of the inner class is also attached to this instance of the outer class. To create instances of an inner class you need an instance of the outer class so that you can use new with the inner class in that instance. Instances of inner classes can directly access all the methods and instance variables of the enclosing class for the instance they are attached to. public class Outer { private int instancevar; public class Inner { public int getouter() { return instancevar; Outer outer = new outer(); Outer.Inner inner = outer.new Inner(); int i = inner.getouter; 4

Extended example of an inner class public class DataStructure { private final static int SIZE = 15; private int[] arrayofints = new int[size]; public DataStructure() { for (int i = 0; i < SIZE; i++) { arrayofints[i] = i; //fill the array public void printeven() { //print out values of even indices of the array private class InnerEvenIterator { private int next = 0; // Begin at the start of the array. public boolean hasnext() { return (next <= SIZE - 1); public int getnext() { int retvalue = arrayofints[next]; next += 2; return retvalue; public static void main(string s[]) { DataStructure ds = new DataStructure(); InnerEvenIterator iterator = ds.new InnerEvenIterator(); while (iterator.hasnext()) { System.out.println(iterator.getNext() + " "); 5

Local and anonymous classes Sometimes an inner class is created specifically to be used in one particular place. In these cases, it makes sense to define the class where it is used rather than separately as a part of the outer class. A local class is an inner class that is defined a method body. An anonymous class is a class that is defined at the exact point where it is used, i.e., where an instance of the class is created. Local classes may be used many times within the the method where they are defined, while anonymous classes are only used once. interface IntRunnable { int run(); public class AnonEx { public static int callrun(intrunnable runnable) { runnable.run(); public static void main(string argv[]) { callrun(new IntRunnable() { // Anonymous class public int run() { return 3 * 5; ); // Close class then call to callrun 6

What use are anonymous classes? Anonymous classes turn out to be particularly useful when creating complex objects from a collection of simpler ones, each with their own methods. It is also often useful for glue code. These styles of programming largely borrow from functional programming, and are generally referred to as higher order. Increasingly this style is influencing object-oriented programming. C# in particular has been highly influenced. 7