Anonymous Classes A short-cut for defining classes when you want to create only one object of the class.

Slides:



Advertisements
Similar presentations
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Advertisements

Written by: Dr. JJ Shepherd
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Cosc 4755 Phone programming: GUI Concepts & Threads.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
OOP in Java – Inner Classes Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
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.
CSE 331 Software Design & Implementation Dan Grossman Spring 2015 GUI Event-Driven Programming (Based on slides by Mike Ernst, Dan Grossman, David Notkin,
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Objects and Classes Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Concurrent Programming and Threads Threads Blocking a User Interface.
UID – Event Handling and Listeners Boriana Koleva
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.
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.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
Nested Classes CompSci 230 S Software Construction.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 15 Event-Driven Programming and.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 15 Event-Driven Programming and.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Swing Threading Nested Classes COMP 401 Fall 2014 Lecture 23 11/25/2014.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
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.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
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.
Inner Classes.
Topic: Inner Classes Course : JAVA PROGRAMMING Paper Code: ETCS-307 Faculty : Dr. Prabhjot Kaur Reader, Dept. of IT 1.
Observer Pattern Context:
Inner Classes 27-Dec-17.
CompSci 230 S Software Construction
Chapter 15 Event-Driven Programming and Animations
Processing Timer Events
CSE 331 Software Design & Implementation
CompSci 230 S Programming Techniques
Lambdas ---anonymous functions---
CSE 331 Software Design and Implementation
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Inner Classes 11/14/ Dec-04 inner_classes.ppt.
CSE 331 Software Design and Implementation
Inner Classes 29-Nov-18.
Web Design & Development Lecture 13
Java Inner Classes.
Class Everything if Java is in a class. The class has a constructor that creates the object. public class ClassName private Field data (instance variables)
A few of the more significant changes and additions. James Brucker
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
9. Threads SE2811 Software Component Design
Final Jim Brucker.
Threads in Java James Brucker.
Inner Classes 17-Apr-19.
Inner Classes 21-Apr-19.
Using threads for long running tasks.
Inner Classes 1-May-19.
Inner Classes 11-May-19.
Inner Classes 18-May-19.
Winter 2019 CMPE212 5/25/2019 CMPE212 – Reminders
CSE 331 Software Design & Implementation
Inner Classes.
Inner Classes 25-Oct-19.
Threads and concurrency / Safety
Presentation transcript:

Anonymous Classes A short-cut for defining classes when you want to create only one object of the class.

Why Anonymous Class? Sometimes we define a class just to create only one instance of the class. Example: a Comparator to sort strings ignoring case Comparator<String> compIgnoreCase = new MyComparator(); Collections.sort( list, compIgnoreCase ); /** Compare strings ignoring case. */ class MyComparator implements Comparator<String> { public int compare(String a, String b) { return a.compareToIgnoreCase(b); }

A class that implements Comparator Anonymous Classes (2) Java lets you define the class and create one object from that class at the same time. The class is anonymous -- it doesn't have a name. Comparator<String> compIgnoreCase = new Comparator<String>() { public int compare(String a, String b) { return a.compareToIgnoreCase(b); } }; Collections.sort( list, compIgnoreCase ); A class that implements Comparator

How to Create Object using an Anonymous Class An anonymous class always extends another class or implements an interface. Name of existing class to extend or existing interface to implement Parenthesis after name, but no semi-colon new Interface_Or_Class( ) { class definition } class definition inside of { }

Example: implement interface Create an object that implements the Comparator interface to compare Strings by length. /** Compare strings by length. */ Comparator<String> compByLength = new Comparator<String>() { /* definition of anonymous class */ public int Compare(String a, String b) { return a.length() - b.length(); } }; Arrays.sort( strings, compByLength );

Example: extend a class Create an object that extends MouseAdapter (a class) to override one method for mouse-click events. The other methods are inherited from MouseAdapter. MouseAdapter click = new MouseAdapter( ) { public void mouseClicked( MouseEvent evt ) { int x = evt.getX(); int y = evt.getY(); System.out.printf("mouse at (%d,%d)", x, y); } };

Example: interface with type param. You can use type parameters in anonymous classes. Example: a Comparator for the Color class to compare colors by amount of red. Comparator<Color> comp = new Comparator<Color>( ) { public int compare(Color c1, Color c2){ return c1.getRed() - c2.getRed(); } };

Rules for Anonymous Classes May have: instance attributes instance methods May not have: constructor static attributes static methods This makes sense! ... the class doesn't have a name.

Parameter for Superclass Constructor You can supply a parameter to Anonymous Class. parameters are passed to the superclass constructor. in this case, anonymous class must extend a class. // Anonymous class extends AbstractAction. // "ON" is passed to AbstractAction // constructor, like using super("ON") Action on = new AbstractAction("ON") { public void actionPerformed(ActionEvent evt) { //TODO perform action } };

Rule: accessing outer attributes An anonymous class can access attributes from the surrounding object. // message is an attribute private String message = "Wake Up!"; void wakeUpCall(Long delay) { // create a TimerTask that prints a msg TimerTask task = new TimerTask() { public void run( ) { System.out.println( message ); } }; Timer timer = new Timer(); timer.schedule( task, delay );

Rule: accessing local variables An anonymous class can access local variables from the surrounding scope only if they are final. void wakeUpCall(Long delay) { final String message = "Wake Up!"; // create a TimerTask that prints a msg TimerTask task = new TimerTask() { public void run( ) { System.out.println( message ); } }; Timer timer = new Timer(); timer.schedule( task, delay );

GUI Code Builders & anonymous class GUI code builders create anonymous classes and use the object all in one statement (no assignment to a variable). This is a common example: JButton mybutton = new JButton("Click Here!"); // define action listener and add it to mybutton mybutton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e){ textfield.setText( "Ouch! Don't press so hard."); } );

This operation is permitted on the event thread only JavaFX Example All UI operations must be done on the Application thread. For example, if you create and show a stage on an ordinary thread: Stage mystage = new CounterView(counter); mystage.show(); JavaFX will throw IllegalStateException: This operation is permitted on the event thread only

Start task on Application Thread A common solution for this is to create a Runnable object for your JavaFX code and run it using: Platform.runLater( Runnable task ); runLater runs the task on the JavaFX Application thread. ? How do we create a Runnable for our CounterView ?

Anonymous Class for Runnable The code we want to run: Anonymous class & Platform.runLater( Runnable ): Counter counter = new Counter(); Stage mystage = new CounterView(counter); mystage.show(); Counter counter = new Counter(); Platform.runLater( new Runnable() { public void run() { Stage mystage = new CounterView(counter); mystage.show(); } } );

Lambda for Runnable The code we want to run: using a Lambda for Platform.runLater( Runnable ): Counter counter = new Counter(); Stage mystage = new CounterView(counter); mystage.show(); Counter counter = new Counter(); Platform.runLater( () -> { Stage mystage = new CounterView(counter); mystage.show(); } );

Summary Use anonymous classes to reduce code when... 1. only need to create one object of the class 2. class is short 3. don't need a constructor, no static fields Guidance: Assign anonymous object to a variable for readability. Don't assign-and-use in one statement. For class with a single method, a Java 8 lambda expression is usually shorter.