CSI 1102 Introduction to Software Design

Slides:



Advertisements
Similar presentations
Interfaces A Java interface is a collection
Advertisements

CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
Java Software Solutions
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Chapter 5: Enhancing Classes
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
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,
Primitive Types vs. Reference Types Variables of primitive types hold the values of the primitive types directly. Variables of reference types hold references.
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
Chapter Day 10. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 10 Questions from last Class?? Problem set 2 posted  10 programs from.
Abstract Classes.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Reference … and Misc Other Topics Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
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.
Chapter Day 9. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 8 Questions from last Class?? Problem set 2 posted  10 programs from.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSE 1301 Lecture 11 Object Oriented Programming Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
6-1 Object-Oriented Design Today we focuses on: –the this reference (Chapter 7) –the static modifier (Chapter 7) –method overloading (Chapter 7)
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
Chapter 5: Enhancing Classes
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
© 2004 Pearson Addison-Wesley. All rights reserved November 7, 2007 Interfaces ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
1 Enhancing Classes  Now we can explore various aspects of classes and objects in more detail  Chapter 5 focuses on: object references and aliases passing.
Chapter 5 Introduction to Defining Classes
1 Object-Oriented Design Now we can extend our discussion of the design of classes and objects Chapter 6 focuses on: software development activities determining.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
SEEM Java – Basic Introduction, Classes and Objects.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
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.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved April 5, 2006 Method Design & Method Overloading ComS 207: Programming I (in Java) Iowa State University,
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
2/23- Interfaces Reference: Java 6.5 and 9.3. PA-4 Review Requirements PA3 – Grading Key PA4 Requirements Doc.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
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.
Chapter 7 Object-Oriented Design
Chapter 5: Enhancing Classes
Variables in Java A variable holds either
Interfaces November 6, 2006 ComS 207: Programming I (in Java)
3 Introduction to Classes and Objects.
Introduction to Classes and Objects
Chapter 5: Enhancing Classes
Creating Objects & String Class
More Object Oriented Programming
Object Oriented Programming
Chapter 4: Writing classes
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through.
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
Java Classes Aliases & Null & This
Object Oriented Programming Review
Packages & Random and Math Classes
Defining Classes and Methods
Outline Creating Objects The String Class The Random and Math Classes
Object-Oriented Design Part 2
Presentation transcript:

CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) 562-5800 x 6277 elsaddik @ site.uottawa.ca abed @ mcrlab.uottawa.ca http://www.site.uottawa.ca/~elsaddik/

Enhancing Classes Now we can explore various aspects of classes and objects in more detail Chapter 5 focuses on: object references and aliases passing objects references as parameters the static modifier wrapper classes nested classes and inner classes interfaces dialog boxes GUI components, events, and listeners

References Recall from Chapter 2 that an object reference variable holds the memory address of an object Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object ChessPiece bishop1 = new ChessPiece(); bishop1

The null Reference An object reference variable that does not currently point to an object is called a null reference An attempt to follow a null reference causes a NullPointerException to be thrown For example String name; declares an object reference variable, but does not create a String object for it to refer to Therefore, the variable name contains a null reference

The null Reference Class NameIsNull { String name; // not initialized therefore null Public void printName() { System.out.println(name.length()); // this will cause an exception }

The this Reference The this reference allows an object to refer to itself Inside a method, the this reference can be used to refer to the currently executing object For example, if(this.position == piece2.position) result = false; clarifies which position is being referenced The this reference refers to the object through which the method containing the code was invoked

The this reference The this reference can also distinguish the parameters of a constructor from the corresponding instance variables with the same names Public Account (Sring owner, long account, double initial) { name = owner; acctNumber = account; balance = initial; }

The this reference The this reference can also distinguish the parameters of a constructor from the corresponding instance variables with the same names Public Account (Sring name, long acctNumber, double balance) { this.name = name; this.acctNumber = acctNumber; this.balance = balance; }

Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable For primitive types: num2 = num1; Before After num1 5 num2 num1 num2 5 12

Reference Assignment For object references, assignment copies the memory location: bishop2 = bishop1; Before bishop1 bishop2 After bishop1 bishop2

Aliases Two or more references that refer to the same object are called aliases of each other One object (and its data) can be accessed using different reference variables Aliases can be useful, but should be managed carefully Changing the object’s state (its variables) through one reference changes it for all of its aliases

Testing Objects for Equality The == operator compares object references for equality, returning true if the references are aliases of each other A method called equals is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator bishop1.equals(bishop2); returns true if both references refer to the same object We can redefine the equals method to return true under whatever conditions we think are appropriate

Garbage Collection All interaction with an object occurs through a reference variable An object is used if we have a reference to it When an object no longer has any valid references to it, it can no longer be accessed by the program It is useless, and is called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use Java Runtime Environment executes a methods that collects all objects marked as garbage

Passing Objects as Parameters Parameters in a Java method are passed by value This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) Passing parameters is essentially like an assignment statement When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other

Passing Objects to Methods What you do using a parameter inside a method may or may not have a permanent effect (outside the method) See ParameterPassing.java (page xxx) See ParameterTester.java (page xxx) See Num.java (page xxx) Note the difference between changing the reference and changing the object that the reference points to

ParameterPassing.java public class ParameterPassing { // sets up 3 variables and illustrate parameter passing public static void main (String [] args) { ParameterTester tester = new ParameterTester(); int a1 = 111; Num a2 = new Num (222); Num a3 = new Num (333); System.out.println("Before ChangeValues: "); System.out.println("a1 a2 a3: " + a1 + " " + a2 + " " + a3); tester.changeValues(a1, a2, a3); System.out.println("After ChangeValues: "); System.out.println("a1 a2 a3: " + a1 + " " + a2 + " " + a3); } }

ParameterTester.java public class ParameterTester { public void changeValues(int f1, Num f2, Num f3) { System.out.println("Before changing the values: "); System.out.println("f1 f2 f3: " + f1 + " " + f2 + " " + f3); f1 = 999; f2.setValue(888); f3 = new Num(777); System.out.println("After changing the values: "); System.out.println("f1 f2 f3: " + f1 + " " + f2 + " " + f3); } }

Num.java public class Num { private int value; // Constructor public Num (int update) { value = update; } // set up a value public void setValue(int update) { value = update; } // toString public String toString() { return value + " "; } }

The results: Parameter passing Before ChangeValues: a1 a2 a3: 111 222 333 Before changing the values: f1 f2 f3: 111 222 333 After changing the values: f1 f2 f3: 999 888 777 After ChangeValues: a1 a2 a3: 111 888 333

What are Static Variables? Associated with the class rather than with an object Static variables sometimes are called class variables Normally, each object has its own data space If a variable is declared as static, only one copy of the variable exists private static float price; Memory space for a static variable is created when the class in which it is declared is loaded All objects created from the class share access to the static variable  Changing the value of a static variable in one object changes it for all others

What are Static Variables? Can we declare Local Variables as static? Can a constant (usually declared through the final modifier) be static?

More about Static Methods Static methods (also called class methods) can be invoked through the class name rather than through a particular object For example, the methods of the Math class are static To make a method static, we apply the static modifier to the method definition Static methods cannot reference instance variables, because instance variables don't exist until an object exists However, they can reference static variables or local variables public static int abs(int num);

More about Static Methods: An example public static int triple (int num) { int result; result = num * 3; return result; } class Helper Because it is static, the method can be invoked as: value = Helper.triple(5);

Static Methods and Variables: CountInstances.java public class CountInstances { public static void main ( String[] args) { Slogan obj; obj = new Slogan("Hello world"); obj = new Slogan("Talk is cheap."); obj = new Slogan("Don't worry, be happy."); System.out.println("Slogans created: " + Slogan.getCount()); } }

Static Methods and Variables: Slogan.java public class Slogan { private String phrase; public static int count = 0; // the constructor public Slogan (String str) { phrase = str; count++; //Every time a Slogan object is created count will be incremented by one } // returns the number of objects of this class created public static int getCount() { return count; } }

What are Wrapper Classes? A wrapper class represents a particular primitive type For example Integer ageObj = new Integer (20); uses the Integer class to create an object which effectively represents the integer 20 as an object Why do we need this? This is useful when a program requires an object instead of a primitive type There is a wrapper class in the Java.lang package for each primitive type, see Figure 5.4 Primitive type (PT) Wrapper Class byte Byte int Integer char Character, etc. for other Primitive Types

Some methods of the Integer class: See p.287 Integer (int value) // constructor: create a new Integer object byte byteValue () double doubleValue () // Return the value of this integer as the corresponding Primitive Type static int ParseInt (String str) // returns the int corresponding to the value stores in the string static String toBinaryString (int num) // returns a string representation of the integer in the corresponding base

Java I/O Java I/O is accomplished using objects that represent streams of data A stream is an ordered sequence of bytes The System.out object represents a standard output stream, which defaults to the monitor screen Reading keyboard input is more complicated… more about it in Chapter 8

Keyboard Input Revisited Input can be read from the keyboard without using the Keyboard class and Wrapper Classes See Wages2.java (page 289): More in Chapter 8 import java.io.*; … BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String name = in.Readline(); int hours = Integer.parseInt(in.readLine());

String myname = new String (“abed”); String myname = new String ( new String (“abed”) );

Nested Classes In addition to containing data and methods, a class can contain another nested class A nested class has access to the variables and methods of the enclosing class, even if they are declared private This is a special relationship and should be used with care Enclosing Class Nested Class

Nested Classes A nested class produces a separate bytecode file If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced: Outside.class Outside$Inside.class It is reasonable to declare the variables in an inner class as public so that the (enclosing) outer class can access them.

Inner Classes: A Non-static nested class An inner class is associated with each instance of the enclosing class & can exist only within an instance of an enclosing class public class TestInner { // create and manipulate an outer object public static void main (String[] args) { Outer out = new Outer(); System.out.println(out); out.changeMessage(); System.out.println(out); } }

Nested Classes: Outer.java public class Outer { private int num; private Inner in1, in2; public Outer() { num = 2365; in1 = new Inner ("Hello"); in2 = new Inner ("Hello again"); } public void changeMessage() { in1.message = "Eat desert first"; in2.message = "Another miracle"; } public String toString() { return in1 + "\n" + in2; } Continued…

Nested classes: Outer.java // The inner class private class Inner { public String message; public Inner (String str) { message = str; } public String toString() { num++; return message + "\nOuter number = " + num; } } }

Nested classes: The output Hello Outer number = 2366 Hello again Outer number = 2367 Eat desert first Outer number = 2368 Another miracle Outer number = 2369

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

Interfaces in Java 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 define a set of methods formally that a class will implement

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

More about 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 or the compiler will produce errors. 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 A class that implements an interface can implement other methods as well A class can implement multiple interfaces class ManyThings implements interface 1, interface2, interface3 { // all methods of all interfaces } The interfaces are listed in the implements clause, separated by commas The class must implement all methods in all interfaces listed in the header

More about Interfaces The Java standard class library contains many helpful interfaces The Comparable interface contains an abstract method called compareTo, which is used to compare two objects The String class implements Comparable which gives us the ability to put strings in alphabetical order The Iterator interface contains methods that allow the user to move easily through a collection of objects

The Comparable Interface The Comparable interface provides a common mechanism for comparing one object to another if (obj1.compareTo(obj2) < 0) System.out.println (“obj1 is less than obj2”); The result is negative is obj1 is less that obj2, 0 if they are equal, and positive if obj1 is greater than obj2

The Iterator Interface The Iterator interface provides a means of moving through a collection of objects, one at a time The hasNext method returns a boolean result (true if there are items left to process) The next method returns an object The remove method removes the object most recently returned by the next method

About GUIs and Dialog Boxes (Much more in Chapter 9) A Graphical User Interface (GUI) is created with at least three kinds of objects components events listeners A GUI component defines a screen element to display information or to allow the user to interact with the program, including: push buttons, text fields, Labels etc. The Swing package contains a class called JOptionPane that simplifies the creation and use of basic dialog boxes

PUSH ME! What is an Dialog Box? A graphical component used to interact with the user, A message dialog displays an output string An input dialog presents a prompt and a single input text field A confirm dialog presents the user with a simple “yes-or-no” question PUSH ME!

Events An event is an object that represents some activity to which we may want to respond For example, we may want our program to perform some action when the following occurs: the mouse is moved a mouse button is clicked the mouse is dragged a graphical button is clicked a keyboard key is pressed a timer expires Events often correspond to user actions, but not always

Events and Listeners The Java standard class library contains several classes that represent typical events Certain objects, such as an applet or a graphical button, generate (fire) an event when it occurs Other objects, called listeners, wait for events to occur We can write listener objects to do whatever we want when an event occurs

About Events and Listeners Generator This object may generate an event Listener This object waits for and responds to an event When an event occurs, the generator calls the appropriate method of the listener, passing an object that describes the event

Listener Interfaces We can create a listener object by writing a class that implements a particular listener interface The Java standard class library contains several interfaces that correspond to particular event categories For example, the MouseListener interface contains methods that correspond to mouse events After creating the listener, we add the listener to the component that might generate the event to set up a formal relationship between the generator and listener

An event listener: PushCounter.java (an extract) import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PushCounter extends JApplet { private int pushes … This.AddActionListener(new MyListener()); public void int () pushes = 0; push = new JButton(“PUSH ME!”); push.AddActionListener(new ButtonListener()); } PUSH ME!

Summary: Enhancing Classes Understand what the following entails Different object references and aliases Passing objects (references) as parameters The static modifier: static variables and methods Wrapper classes for primitive data types Nested and inner classes Interfaces for software design GUI components, dialog boxes, events, and listeners

Thank You!