Java Implementation Software Construction Lecture 6.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

 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).
Java Implementation: Part 1 S CompSci 230 Software Construction.
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
Abstract Class and Interface
Java Review Interface, Casting, Generics, Iterator.
OBJECT-ORIENTED PROGRAMMING CONCEPTS (Review). What is an Object? What is an Object? Objects have states and behaviors. Example: A dog has states - color,
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Dale Roberts GUI Programming using Java - Mouse Events Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
© The McGraw-Hill Companies, 2006 Chapter 14 Abstraction, inheritance and interfaces.
1 Inheritance. 2 One class inherits from another if it describes a specialized subset of objects Terminology: inheritschild class subclass –the class.
Event Handling Events and Listeners Timers and Animation.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
Object Oriented Paradigm Programming Paradigms En Mohd Norafizal A.Aziz.
Interfaces besides classes, Java recognizes another type, an interface interface is used to completely shield off all implementation from the programmer.
Question of the Day  Write valid mathematical equation using: one addition operator (‘+’) one equality operator (‘=’)  Should have equal values.
Chapter 4 Objects and Classes.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Object Oriented Programming Concepts Fatih University Ceng-104-A Introduction to Object Oriented Programming Harun Reşit Zafer This is a slide version.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Implementation: Part 3 Software Construction Lecture 8.
Chapter 11 Java AWT Part I: Mouse Events (Optional) Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Computer Science and Engineering College of Engineering The Ohio State University Interfaces The credit for these slides goes to Professor Paul Sivilotti.
The Java Programming Language
Java Programming: Guided Learning with Early Objects
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
CompSci 230 S Software Construction
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
INTERFACES More OO Concepts. Interface Topics Using an interface Interface details –syntax –restrictions Create your own interface Remember polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
12/5/00SEM107, Kamin & ReddyReview - 34 Events Event types Catching different event types Getting information from components and events Distinguishing.
LECTURE 9: INTERFACES & ABSTRACT CLASSES CSC 212 – Data Structures.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
Understand the difference between applets and applications Identify meaningful applet resources for academic subjects Create and demonstrate a basic Java.
Object Oriented Programming.  Interface  Event Handling.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Mouse Listeners Moving the mouse will also generate events like the Timer –To have your program respond, you must implement either or both of MouseListener.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
What Is a Package? A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 10.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
By : Robert Apeldorn. What is OOP?  Object-oriented programming is a programming paradigm that uses “objects” to design applications and computer programs.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
More About Java and Java How to Program By Deitel & Deitel.
CompSci 230 S Programming Techniques
University of Central Florida COP 3330 Object Oriented Programming
Interfaces.
البرمجة الكينونية بلغة جافا 1294
GUI Programming using Java - Mouse Events
Week 6 Object-Oriented Programming (2): Polymorphism
Web Design & Development Lecture 12
Advanced Java Programming
Presentation transcript:

Java Implementation Software Construction Lecture 6

Agenda 2  Topics:  Interfaces in Java  Reference data types  Abstract classes in Java  Overview of generics in Java  Reading  In The Java Tutorials:The Java Tutorials  What is an Interface?, in the Object-Oriented Programming Concepts Lesson What is an Interface?Object-Oriented Programming Concepts  The Interfaces and Inheritance LessonInterfaces and Inheritance  Why Use Generics? in the Generics (Updated) Lesson. Why Use Generics?Generics (Updated)

Learning objectives for this week 3  Students will be competent at implementing OO designs in Java  Interfaces, reference data types, abstract classes, intro to generics  The lectures will give you the basic “theory”, but they won’t give you a “working understanding” – you have to do the hard- yards of putting these ideas into practice.  You won’t even understand the theory, if you listen passively to lectures. I’ll try to help you “learn how to learn” from the Java tutorials.  You’ll get many chances to develop your understanding in your lab assignments for this course.

Interfaces, in UML (review) 4  Interfaces specify behaviour (a public contract), without data or implementation.  Interfaces are drawn like classes, but without attributes, and with the keyword >  A dotted open-triangle arrow, from a class to an interface, means that “the class implements this interface”.  We also say that “the class fulfils the contract specified by this interface ”, or that it “realizes the interface.”  Note that interfaces define methods but not attributes.  A password allows a secureLogin().

Interfaces in Java 5  An Interface is like a Class, with no bodies in the methods. It may define constants ( public static final ) but no runtime variables.  Usually, an Interface is public.  An interface provides a standard way to access a class which could be implemented in many different ways.  The Java Tutorials:  “There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a ‘contract’ that spells out how their software interacts.”  “Each group should be able to write their code without any knowledge of how the other group's code is written.”  “Generally speaking, interfaces are such contracts.”

Implementations, in Java 6  In Java, a class which implements an interface must provide an implementation of every method defined within the interface  A class may implement some additional methods (but these extra methods aren’t accessible through this interface)  Beware: adding another method to an existing Interface will “break” every current implementation of this Interface!  A class can implement many interfaces.  An Interface can extend other Interfaces.  Extension is the preferred way to add new methods to an Interface.  (Do you understand why?)  In Java, classes are less extendible than interfaces, because a Class can extend at most one other Class (“single inheritance”). class MountainBike extends Bicycle { … }

Example 1 7 public interface Bicycle { void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } class ACMEBicycle implements Bicycle { int cadence = 0; void changeCadence(int newValue) { cadence = newValue; } \\ an implementation may be incorrect! void changeGear(int newValue) {} void speedUp(int increment) {} void applyBrakes(int decrement) {} } \\ an implementation usually has variables

Example 2 8 public interface GroupedInterface extends Interface1, Interface2, Interface3 { // constant declarations // base of natural logarithms double E = ; // method signatures void doSomething( int i, double x ); int doSomethingElse( String s ); }

Example 3 9 public interface EventListener { // No constants // No method signatures! }  “A tagging interface that all event listener interfaces must extend.” [  Why?  At first glance, this is worse than useless! One more name for the Java programmer to remember…  This interface allows programmers, and the Java compiler, to distinguish event-listeners from all other types of classes and interfaces.  Event-listeners are important, and they behave quite differently to a regular class. (Later, you’ll learn about inversion of control…)

MouseListener in java.awt.event 10 public interface MouseListener extends EventListenerMouseListenerEventListener The listener interface for receiving “interesting” mouse events (press, release, click, enter, and exit) on a component. (To track mouse moves and mouse drags, use the MouseMotionListener.) All Known Subinterfaces: MouseInputListener All Known Implementing Classes: AWTEventMulticasterAWTEventMulticaster, BasicButtonListener, BasicComboPopup.InvocationMouseHandler, BasicComboPopup.ListMouseHandler, BasicDesktopIconUI.MouseInputHandler, …BasicButtonListenerBasicComboPopup.InvocationMouseHandler BasicComboPopup.ListMouseHandlerBasicDesktopIconUI.MouseInputHandler public interface MouseListener extends EventListener { mouseClicked( MouseEvent e ); mouseEntered( MouseEvent e ); mouseExited( MouseEvent e ); mousePressed( MouseEvent e ); mouseReleased( MouseEvent e ); } public interface MouseMotionListener extends EventListener { mouseDragged( MouseEvent e ); mouseMoved( MouseEvent e ); } public interface MouseInputListener extends MouseListener, MouseMotionListener { // this interface has 7 method signatures, can you list them? }

UML: Review of Interfaces. Packages. 11

Using an Interface as a Type 12  “When you define a new interface, you are defining a new reference data type.  “You can use interface names anywhere you can use any other data type name.  “If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.” [  Example on the next slide:  A method for finding the largest object in a pair of objects, for any objects that are instantiated from a class that implements Relatable. public interface Relatable { public int isLargerThan( Relatable other ); }

Using an Interface as a Type 13 public Object findMax(Object object1, Object object2) { Relatable obj1 = (Relatable)object1; Relatable obj2 = (Relatable)object2; if( (obj1).isLargerThan(obj2) > 0 ) return object1; else return object2; }  If comparisons are important in your application, then you’ll be able to write very elegant code!  You can write z.findMax(x, y), if x and y are instances of any class which e xtends Relatable.

Using an Interface as a Type: Dangers 14 public Object findMax( Object object1, Object object2 ) { Relatable obj1 = (Relatable)object1; Relatable obj2 = (Relatable)object2; if( (obj1).isLargerThan(obj2) > 0 ) return object1; else return object2; }  Watch out for type mismatches!! We’d get a compile-time error if  (object1).isLargerThan(object2) were in the body of this method,  we invoked it as z.findMax(x,y), for any instance x of a class that doesn’t extend Relatable, or if  we invoked it as x.findLargest(y,z), if y.isLargerThan() does not accept z as a parameter.  If it’s easy for a programmer (and a compiler) to determine the class of all arguments in every method-call, then you’ll avoid these dangers.

Typing Rules 15  The typing rules for interfaces are similar to those for classes.  A reference variable of interface type T can refer to an instance of any class that implements interface T or a sub-interface of T.  Through a reference variable of interface type T, methods defined by T and its super interfaces can be called. interface I1 { public void m1(); public void m2(); } class c1 implements I1 { public void m1() {} public void m2() {} } interface I2 extends I1 { public void m3(); } class c2 implements I2 { public void m1() {} public void m2() {} public void m3() {} } C1 a = new C1(); \\ a is a reference variable of type C1 C1 b = new C1(); I1 p = a; \\ p is a reference variable of type I1 p.m1(); C2 c = new C2(); I2 q = c; \\ q is a reference variable of type I2 q.m1(); q.m2(); «realize»

instanceof 16  You can use the instanceof operator to test an object to see if it implements an interface, before you invoke a method in this interface.  This might improve readability and correctness.  This might be a hack.  Where possible, you should extend classes and interfaces to obtain polymorphic behaviour, rather than making a runtime check. if( b instanceof Bounceable ) { b.hitWall( "Wall A" ); } else { \\ abort, with an error message to the console throw new AssertionError( b ); } Date somedate = new Date(); \\ throw an exception if somedate is not Relatable. assert( Date instanceof Relatable ); \\ See