Java & Inner Classes L. Grewe. Kinds of of Classes Top level classes Top level classes Declared inside packageDeclared inside package Visible throughout.

Slides:



Advertisements
Similar presentations
Introduction to classes Sangeetha Parthasarathy 06/11/2001.
Advertisements

DATA STRUCTURES Lecture: Interfaces Slides adapted from Prof. Steven Roehrig.
Inner Classes. Nested Classes  An nested class is a class that is defined inside another class.  To this point we have only studied top-level classes.
Programming With Java ICS201 University Of Hail1 Chapter 13 Inner Classes.
EC-241 Object-Oriented Programming
Inner Classes in Java CMSC 432 Shon Vick. 2 Conceptual Structure package p 1 class A 1 class A 2... class A n... package n class A 1 class A 2... class.
OOP in Java – Inner Classes Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Nested Classes Yoshi Modified from:
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Unit 08 & 091 Nested Classes Introduction Inner Classes Local Classes Anonymous Classes Exercises.
Road Map Introduction to object oriented programming. Classes
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
Access to Names Namespaces, Scopes, Access privileges.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
Inner Classes. Lecture Objectives Learn about inner classes. Know the differences between static and non- static inner classes. Designing and using inner.
OOP in Java – Inner Classes Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
OOP in Java – Inner Classes Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
Inner Classes. Inner classes All the classes so far have been “top level” It is possible (and useful) to define a class inside another class Inner classes.
Inner Classes in Java. Overview Inner class – one class nested inside another – static (i.e. class) rarely if ever used – member (i.e. instance) – anonymous.
Iterators CS 367 – Introduction to Data Structures.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Abstract and Nested Classes
Chapter 8: Inner Classes. You're an OO programmer, so you know that for reuse and flexibility/extensibility you need to keep your classes specialized.
Lecture 10 Documentation, Garbage Collection, and Nested Classes/Interfaces.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
2-Dec-15 Inner Classes. 2 Inner classes All the classes so far have been “top level” It is possible (and useful) to define a class inside another class.
Java Inner Classes. Interfaces interface KeyListener { public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent.
2-Dec-15 Inner Classes By Alguien Soy. 2 Inner classes All the classes so far have been “top level” It is possible (and useful) to define a class inside.
CS884 (Prasad)java11Extn1 Java 1.1 Extensions Nested classes static public/protected/private.
An Advanced Code Pattern: Inner Classes CSE301 University of Sunderland Harry R. Erwin, PhD Half Lecture.
Nested Classes CompSci 230 S Software Construction.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Generic Programming and Inner classes ge·ner·ic 1a : relating or applied to or descriptive of all members of a genus, species, class, or group : common.
Swing Threading Nested Classes COMP 401 Fall 2014 Lecture 23 11/25/2014.
Object Oriented Programming in Java Habib Rostami Lecture 10.
Advanced Java class Nested Classes & Interfaces. Types of Nested Classes & Interfaces top-level nested –classes –interfaces inner classes –member –local.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
N ESTED C LASSES -1. T YPES OF N ESTED C LASSES & I NTERFACES top-level nested classes interfaces inner classes member local named anonymous.
Advanced Programming in C
Inner Classes.
Topic: Inner Classes Course : JAVA PROGRAMMING Paper Code: ETCS-307 Faculty : Dr. Prabhjot Kaur Reader, Dept. of IT 1.
Inner Classes 27-Dec-17.
Classes and Objects Introduced
CompSci 230 S Software Construction
CompSci 230 S Programming Techniques
Nested class.
Inner Classes 11/14/ Dec-04 inner_classes.ppt.
Anonymous Classes A short-cut for defining classes when you want to create only one object of the class.
Overloading and Overriding
Inner Classes 29-Nov-18.
Lecture 26: Advanced List Implementation
Inner Classes.
Java Inner Classes.
Namespaces, Scopes, Access privileges
Inner Classes 17-Apr-19.
Inner Classes 21-Apr-19.
Inner Classes 1-May-19.
Inner Classes 11-May-19.
Inner Classes 18-May-19.
CSE 143 Lecture 21 Advanced List Implementation
Inner Classes.
Inner Classes 25-Oct-19.
Presentation transcript:

Java & Inner Classes L. Grewe

Kinds of of Classes Top level classes Top level classes Declared inside packageDeclared inside package Visible throughout package, perhaps furtherVisible throughout package, perhaps further Normally, although not always, declared in their own fileNormally, although not always, declared in their own file public classes must be defined in their own file public classes must be defined in their own file Nested and inner classes Nested and inner classes Declared inside class (or method)Declared inside class (or method) can be visible only to outer class, or have wider visibilitycan be visible only to outer class, or have wider visibility

Kinds of nested/inner classes Inner class Inner class defined inside another classdefined inside another class but each instance of an inner class is transparently associated with an instance of the outer classbut each instance of an inner class is transparently associated with an instance of the outer class method invocations can be transparently redirected to outer instancemethod invocations can be transparently redirected to outer instance Anonymous inner classes Anonymous inner classes unnamed inner classesunnamed inner classes Nested class Nested class defined inside another classdefined inside another class has access to private members of enclosing classhas access to private members of enclosing class But just a normal classBut just a normal class

Inner Classes Description Description Class defined in scope of another classClass defined in scope of another class Property Property Can directly access all variables & methods of enclosing class (including private fields & methods)Can directly access all variables & methods of enclosing class (including private fields & methods) Example Example public class OuterClass { public class InnerClass { public class InnerClass { }}

Inner Classes May be named or anonymous May be named or anonymous Useful for Useful for Logical grouping of functionalityLogical grouping of functionality Data hidingData hiding Linkage to outer classLinkage to outer class Examples Examples Iterator for Java CollectionsIterator for Java Collections ActionListener for Java GUI widgetsActionListener for Java GUI widgets

Motivating Example MyList MyList public class MyList { private Object [ ] a; private Object [ ] a; private int size; private int size;} Want to make MyList implement Iterable Want to make MyList implement Iterable skipping generic types at the momentskipping generic types at the moment need to be able to return an Iteratorneed to be able to return an Iterator

MyIterator Design public class MyIterator implements Iterator { private MyList list; private MyList list; private int pos; private int pos; MyIterator(MyList list) { MyIterator(MyList list) { this.list = list; this.list = list; pos = 0; pos = 0; } public boolean hasNext() { public boolean hasNext() { return pos < list.size; return pos < list.size; } public Object next() { public Object next() { return list.a[pos++]; return list.a[pos++]; }}

MyIterator Design Problems Problems Need to maintain reference to MyListNeed to maintain reference to MyList Need to access private data in MyListNeed to access private data in MyList Solution Solution Define MyIterator as inner class for MyListDefine MyIterator as inner class for MyList

MyIterator Design Code Code public class MyList implements Iterable { private Object [ ] a; private Object [ ] a; private int size; private int size; public Iterator iterator() { return new MyIterator(); } public Iterator iterator() { return new MyIterator(); } public class MyIterator implements Iterator { public class MyIterator implements Iterator { private int pos = 0; private int pos = 0; public boolean hasNext() { return pos < size; } public boolean hasNext() { return pos < size; } public Object next() { return a[pos++]; } public Object next() { return a[pos++]; } }}

Inner Classes Inner class instance Inner class instance Has association to an instance of outer classHas association to an instance of outer class Must be instantiated with an enclosing instanceMust be instantiated with an enclosing instance Is tied to outer class object at moment of creation (can not be changed)Is tied to outer class object at moment of creation (can not be changed) MyList MyIterator

Method resolution When resolving a method call on an unspecified object When resolving a method call on an unspecified object first see if the method can be resolved on the inner object.first see if the method can be resolved on the inner object. If not, see if the method can be resolved on the corresponding instance of the outer objectIf not, see if the method can be resolved on the corresponding instance of the outer object If nested multiple levels, keep on lookingIf nested multiple levels, keep on looking

Creating/Referring to inner classes Assume class A defines an inner class B Assume class A defines an inner class B Inside instance methods of A, just use B as the type of references to the inner class and use new B(…) to create instances Inside instance methods of A, just use B as the type of references to the inner class and use new B(…) to create instances newly created B object associated with A object referenced by thisnewly created B object associated with A object referenced by this Outside of A, use A.B to name the inner class Outside of A, use A.B to name the inner class If you need to create an instance of B associated with a specific A object a, outside of an instance method on a If you need to create an instance of B associated with a specific A object a, outside of an instance method on a use a.new B()use a.new B() it is very rare for you to need to do thisit is very rare for you to need to do this

Accessing Outer Scope Code Code public class OC {// outer class int x = 2; int x = 2; public class IC {// inner class public class IC {// inner class int x = 6; int x = 6; public void getX() {// inner class method public void getX() {// inner class method int x = 8; int x = 8; System.out.println( x );// prints 8 System.out.println( x );// prints 8 System.out.println( this.x );// prints 6 System.out.println( this.x );// prints 6 System.out.println( OC.this.x );// prints 2 System.out.println( OC.this.x );// prints 2 } }}

Anonymous Inner Class Doesn’t name the class Doesn’t name the class inner class defined at the place where you create an instance of it (in the middle of a method) inner class defined at the place where you create an instance of it (in the middle of a method) Useful if the only thing you want to do with an inner class is create instances of it in one locationUseful if the only thing you want to do with an inner class is create instances of it in one location In addition to referring to fields/methods of the outer class, can refer to final local variables In addition to referring to fields/methods of the outer class, can refer to final local variables

Syntax for anonymous inner classes use new Foo() { public int one() { return 1; } public int add(int x, int y) { return x+y; } }; use new Foo() { public int one() { return 1; } public int add(int x, int y) { return x+y; } }; to define an anonymous inner class that: to define an anonymous inner class that: extends class Fooextends class Foo defines methods one and adddefines methods one and add

MyList without anonymous inner class Code Code public class MyList implements Iterable { private Object [ ] a; private Object [ ] a; private int size; private int size; public Iterator iterator() { return new MyIterator(); } public Iterator iterator() { return new MyIterator(); } public class MyIterator implements Iterator { public class MyIterator implements Iterator { private int pos = 0; private int pos = 0; public boolean hasNext() { return pos < size; } public boolean hasNext() { return pos < size; } public Object next() { return a[pos++]; } public Object next() { return a[pos++]; } }}

MyList with anonymous inner class Code Code public class MyList implements Iterable { private Object [ ] a; private Object [ ] a; private int size; private int size; public Iterator iterator() { return new Iterator () { public Iterator iterator() { return new Iterator () { private int pos = 0; private int pos = 0; public boolean hasNext() { return pos < size; } public boolean hasNext() { return pos < size; } public Object next() { return a[pos++]; } public Object next() { return a[pos++]; } }}

Nested class Declared like a standard inner class, except you say “static class” rather than “class”. Declared like a standard inner class, except you say “static class” rather than “class”. For example: class LinkedList { static class Node { Object head; Node tail; } Node head; } For example: class LinkedList { static class Node { Object head; Node tail; } Node head; }

Nested classes An instance of an inner class does not contain an implicit reference to an instance of the outer class An instance of an inner class does not contain an implicit reference to an instance of the outer class Still defined within outer class, has access to all the private fields Still defined within outer class, has access to all the private fields Use if inner object might be associated with different outer objects, or survive longer than the outer object Use if inner object might be associated with different outer objects, or survive longer than the outer object Or just don’t want the overhead of the extra pointer in each instance of the inner objectOr just don’t want the overhead of the extra pointer in each instance of the inner object

Using inner classes in GUIs javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndDisplayGUI(); createAndDisplayGUI(); } }); }); button.addActionListener (new ActionListener() { public void actionPerformed (ActionEvent evt) { public void actionPerformed (ActionEvent evt) { System.out.println(“Button pushed”); System.out.println(“Button pushed”); } }); });

Using inner class in a Count GUI class Counter { int counter = 0; public Counter() { … final JLabel count = new JLabel("0"); JButton increment = new JButton("Increment"); increment.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent a) { counter++; count.setText(Integer.toString(counter)); repaint(); }});

What to notice Inside actionPerformed, we referenced: Inside actionPerformed, we referenced: the value fieldthe value field the display local variablethe display local variable the this corresponding to the Counterthe this corresponding to the Counter when we invoked repaint() when we invoked repaint() you can’t repaint an ActionListeneryou can’t repaint an ActionListener