Designing Classes Chapter 3. Contents Encapsulation Specifying Methods Java Interfaces – Writing an Interface – Implementing an Interface – An Interface.

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

Interfaces A Java interface is a collection
Inheritance Inheritance Reserved word protected Reserved word super
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
Polymorphism Chapter 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
More Inheritance Abstract Classes Interfaces Briana B. Morrison CSE 1302C Spring 2010.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 9: Polymorphism Coming up: Binding.
Designing Classes Chapter 3. 2 Chapter Contents Encapsulation Specifying Methods Java Interfaces Writing an Interface Implementing an Interface An Interface.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Chapter 5: Keyboard I/O & Simple GUI’s Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Abstract Classes.
1 Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 7 “Object Oriented Design”
Interfaces A Java interface is a collection of constants and abstract methods with a name that looks like a class name, i.e. first letter is capitalized.
INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Object Oriented Design and UML
Writing Classes (Chapter 4)
© 2004 Pearson Addison-Wesley. All rights reserved November 9, 2007 Method Design & Method Overloading ComS 207: Programming I (in Java) Iowa State University,
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.
© 2004 Pearson Addison-Wesley. All rights reserved November 7, 2007 Interfaces ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
111 Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract,
Chapter 9 Polymorphism. Chapter Scope The role of polymorphism Dynamic binding Using inheritance for polymorphism Exploring Java interfaces in more detail.
COS 312 DAY 14 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress Report Over due – Next progress report is March 26 Assignment 4 Due Assignment 5.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 6: Object-Oriented Design.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
Designing Classes Prelude © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions with Java, 4e Frank.
Designing Classes Chapter 3. 2 Chapter Contents Encapsulation Specifying Methods Java Interfaces Writing an Interface Implementing an Interface An Interface.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
Java Software Solutions Lewis and Loftus Chapter 9 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Enhanced Class Design -- Introduction.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Side effects A side effect is anything that happens in a method other than computing and/or returning a value. Example: public class hello { public int.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 8 Inheritance 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
1 Lecture 8 b Data Structures b Abstraction b The “Structures” package b Preconditions and postconditions b Interfaces b Polymorphism b Vector class b.
2/23- Interfaces Reference: Java 6.5 and 9.3. PA-4 Review Requirements PA3 – Grading Key PA4 Requirements Doc.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
COS 312 DAY 16 Tony Gauvin.
Chapter 5: Enhancing Classes
Interfaces November 6, 2006 ComS 207: Programming I (in Java)
Encapsulation and Java Interface
About the Presentations
Chapter 4: Writing Classes
Wrapper Classes ints, doubles, and chars are known as primitive types, or built-in types. There are no methods associated with these types of variables.
Slides by Steve Armstrong LeTourneau University Longview, TX
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Chapter 5: Enhancing Classes
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Chapter 8 Inheritance.
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object-Oriented Design Part 2
Presentation transcript:

Designing Classes Chapter 3

Contents Encapsulation Specifying Methods Java Interfaces – Writing an Interface – Implementing an Interface – An Interface as a Data Type – Generic Types Within an Interface – Type Casts Within an Interface Implementation – Extending an Interface – Interfaces Versus Abstract Classes – Named Constants Within an Interface

Contents Choosing Classes – Identifying Classes – CRC Cards – The Unified Modeling Language Reusing Classes

Encapsulation Hides the fine detail of the inner workings of the class – The implementation is hidden – Often called "information hiding" Part of the class is visible – The necessary controls for the class are left visible – The class interface is made visible – The programmer is given only enough information to use the class

Encapsulation Fig. 3-1 An automobile's controls are visible to the driver, but its inner workings are hidden.

Abstraction A process that has the designer ask what instead of why – What is it you want to do with the data – What will be done to the data The designer does not consider how the class's methods will accomplish their goals The client interface is the what The implementation is the how

Abstraction Fig. 3-2 An interface provides well-regulated communication between a hidden implementation and a client.

Specifying Methods Specify what each method does Precondition – Defines responsibility of client code Postcondition – Specifies what will happen if the preconditions are met

Specifying Methods Responsibility – Precondition implies responsibility for guarantee of meeting certain conditions Where to place responsibility – Client? or … – Method? Best to comment this clearly before method's header – Also good to have method check during debugging

Specifying Methods Assertion is statement of truth about aspect of a program's logic – Like a boolean statement that should be true at a certain point Assertions can be written as comments to identify design logic // Assertion: intVal >= 0 Assert Statement – assert someVal < 0; – If false, program execution terminates

Java Interface A program component that contains – Public constants – Signatures for public methods – Comments that describe them Begins like a class definition – Use the word interface instead of class

Writing an Interface Consider geometric figures which have both a perimeter and an area We want classes of such objects to have such methods – And we want standardization signatures View example of the interface Measurable View example

Java Interface Example Recall class Name from previous chapterclass Name Consider an interface for the class Name – View example listing View example Note – Comments of method purpose, parameters, pre- and post-conditions – Any data fields should be public, final, and static – Interface methods cannot be final

Implementing an Interface A class that implements an interface must state so at start of definition with implements clause The class must implement every method declared in the interface Multiple classes can implement the same interface A class can implement more than one interface

Implementing an Interface Fig. 3-3 The files for an interface, a class that implements the interface, and the client.

An Interface as a Data Type An interface can be used as a data type or …

Generic Types Within an Interface Recall class OrderedPair from Chapter 2 OrderedPair – Note the setPair method Consider an interface Pairable that declares this method A class that implements this interface could begin with the statement

The Interface Comparable Method compareTo compares two objects, say x and y – Returns signed integer – Returns negative if x < y – Returns zero if x == y – Returns positive if x > y

The Interface Comparable Consider a class Circle – Methods equals, compareTo – Methods from Measurable View source code View source Note – Implements Measurable interface – Shown with two alternative versions of compareTo

Extending an Interface Use inheritance to derive an interface from another When an interface extends another – It has all the methods of the inherited interface – Also include some new methods Also possible to combine several interfaces into a new interface – Not possible with classes

Interfaces Versus Abstract Classes Purpose of interface similar to purpose of abstract class But … an interface is not a base class – It is not a class of any kind Use an abstract base class when – You need a method or private data field that classes will have in common Otherwise use an interface

Named Constants Within an Interface An interface can contain named constants – Public data fields initialized and declared as final Consider an interface with a collection of named constants – Then derive variety of interfaces that can make use of these constants

Choosing Classes Look at a prospective system from a functional point of view Ask – What or who will use the system – What can each actor do with the system – Which scenarios involve common goals Use a case diagram

Choosing Classes Fig. 3-4 A use case diagram for a registration system

Identifying Classes Describe the system – Identify nouns and verbs Nouns suggest classes – Students – Transactions – Customers Verbs suggest appropriate methods – Print an object – Post a transaction – Bill the customer

Identifying Classes Fig. 3-5 A description of a use case for adding a course

CRC Cards Index cards – each card represents one class Write a descriptive name for class at top List the class's responsibilities – The methods Indicate interactions – The collaborations These are CRC cards "Class-Responsibility-Collaboration"

CRC Cards Fig. 3-6 A class-responsibility-collaboration card

Unified Modeling Language Used to illustrate a system's classes and relationships Provides a class diagram – Class name – Attributes – Operations Fig. 3-7 A class representation that can be part of a class diagram.

Unified Modeling Language Fig. 3-8 UML notation for a base class Student and two derived classes

Unified Modeling Language Fig. 3-9 A class diagram showing the base class Student and two derived classes

Unified Modeling Language Fig Part of a UML class diagram with associations.

Reusing Classes Much software combines: – Existing components – New components When designing new classes – Plan for reusability in the future – Make objects as general as possible – Avoid dependencies that restrict later use by another programmer

Interfaces A Java interface is a collection of abstract methods and constants An abstract method is a method header without a method body An abstract method can be declared using the modifier abstract, but because all methods in an interface are abstract, usually it is left off An interface is used to establish a set of methods that a class will implement

Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } interface is a reserved word None of the methods in an interface are given a definition (body) A semicolon immediately follows each method header

Interfaces An interface cannot be instantiated Methods in an interface have public visibility by default A class formally implements an interface by – stating so in the class header – providing implementations for each abstract method in the interface If a class asserts that it implements an interface, it must define all methods in the interface

Interfaces public class CanDo implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition

Interfaces A class that implements an interface can implement other methods as well In addition to (or instead of) abstract methods, an interface can contain constants When a class implements an interface, it gains access to all its constants

Interfaces An example of an interface in use

SecretTest.java //******************************************************************** // SecretTest.java Java Foundations // // Demonstrates the use of a formal interface. //******************************************************************** public class SecretTest { // // Creates a Secret object and exercises its encryption. // public static void main (String[] args) { Secret hush = new Secret ("Wil Wheaton is my hero!"); System.out.println (hush); hush.encrypt(); System.out.println (hush); hush.decrypt(); System.out.println (hush); }

Encryptable.java //******************************************************************** // Encryptable.java Java Foundations // // Represents the interface for an object that can be encrypted // and decrypted. //******************************************************************** public interface Encryptable { public void encrypt(); public String decrypt(); }

Secret.java //******************************************************************** // Secret.java Java Foundations // // Represents a secret message that can be encrypted and decrypted. //******************************************************************** import java.util.Random; public class Secret implements Encryptable { private String message; private boolean encrypted; private int shift; private Random generator; // // Constructor: Stores the original message and establishes // a value for the encryption shift. // public Secret (String msg) { message = msg; encrypted = false; generator = new Random(); shift = generator.nextInt(10) + 5; } (more…)

Secret.java // // Encrypts this secret using a Caesar cipher. Has no effect if // this secret is already encrypted. // public void encrypt () { if (!encrypted) { String masked = ""; for (int index=0; index < message.length(); index++) masked = masked + (char)(message.charAt(index)+shift); message = masked; encrypted = true; } (more…)

Secret.java // // Decrypts and returns this secret. Has no effect if this // secret is not currently encrypted. // public String decrypt() { if (encrypted) { String unmasked = ""; for (int index=0; index < message.length(); index++) unmasked = unmasked + (char)(message.charAt(index)-shift); message = unmasked; encrypted = false; } return message; } // // Returns true if this secret is currently encrypted. // public boolean isEncrypted() { return encrypted; } (more…)

Secret.java // // Returns this secret (may be encrypted). // public String toString() { return message; }

Interfaces A class can implement multiple interfaces The interfaces are listed in the implements clause The class must implement all methods in all interfaces listed in the header class ManyThings implements interface1, interface2 { // all methods of both interfaces }

Interfaces The Java standard class library contains many helpful interfaces The Comparable interface contains one abstract method called compareTo, which is used to compare two objects We discussed the compareTo method of the String class in Chapter 4 The String class implements Comparable, giving us the ability to put strings in lexicographic order

The Comparable Interface Any class can implement Comparable to provide a mechanism for comparing objects of that type if (obj1.compareTo(obj2) < 0) System.out.println ("obj1 is less than obj2"); The value returned from compareTo should be negative is obj1 is less that obj2, 0 if they are equal, and positive if obj1 is greater than obj2 When a programmer designs a class that implements the Comparable interface, it should follow this intent

The Comparable Interface It’s up to the programmer to determine what makes one object less than another For example, you may define the compareTo method of an Employee class to order employees by name (alphabetically) or by employee number The implementation of the method can be as straightforward or as complex as needed for the situation

The Iterator Interface As we discussed in Chapter 4, an iterator is an object that provides a means of processing a collection of objects one at a time An iterator is created formally by implementing the Iterator interface, which contains three methods The hasNext method returns a boolean result – true if there are items left to process The next method returns the next object in the iteration The remove method removes the object most recently returned by the next method

The Iterator Interface By implementing the Iterator interface, a class formally establishes that objects of that type are iterators The programmer must decide how best to implement the iterator functions Once established, the for-each version of the for loop can be used to process the items in the iterator

Interfaces You could write a class that implements certain methods (such as compareTo ) without formally implementing the interface ( Comparable ) However, formally establishing the relationship between a class and an interface allows Java to deal with an object in certain ways Interfaces are a key aspect of object-oriented design in Java

Polymorphism via Interfaces An interface name can be used as the type of an object reference variable Speaker current; The current reference can be used to point to any object of any class that implements the Speaker interface The version of speak that the following line invokes depends on the type of object that current is referencing current.speak();

Polymorphism via Interfaces Suppose two classes, Philosopher and Dog, both implement the Speaker interface, providing distinct versions of the speak method In the following code, the first call to speak invokes one version and the second invokes another Speaker guest = new Philospher(); guest.speak(); guest = new Dog(); guest.speak();

Event Processing Polymorphism plays an important role in the development of a Java graphical user interface As we’ve seen, we establish a relationship between a component and a listener JButton button = new JButton(); button.addActionListener(new MyListener()); Note that the addActionListener method is accepting a MyListener object as a parameter In fact, we can pass the addActionListener method any object that implements the ActionListener interface

Event Processing The source code for the addActionListener method accepts a parameter of type ActionListener (the interface) Because of polymorphism, any object that implements that interface is compatible with the parameter reference variable The component can call the actionPerformed method because of the relationship between the listener class and the interface Extending an adapter class to create a listener represents the same situation; the adapter class implements the appropriate interface already