www site uottawa caelsaddik CSI 1102 Introduction to

  • Slides: 53
Download presentation
www. site. uottawa. ca/~elsaddik CSI 1102 Introduction to Software Design Prof. Dr. -Ing. Abdulmotaleb

www. site. uottawa. ca/~elsaddik 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/ 1 (c) elsaddik

www. site. uottawa. ca/~elsaddik Enhancing Classes 2 (c) elsaddik Now we can explore various

www. site. uottawa. ca/~elsaddik Enhancing Classes 2 (c) elsaddik 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

www. site. uottawa. ca/~elsaddik References ØRecall from Chapter 2 that an object reference variable

www. site. uottawa. ca/~elsaddik 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 Chess. Piece bishop 1 = new Chess. Piece(); bishop 1 3 (c) elsaddik

www. site. uottawa. ca/~elsaddik The null Reference ØAn object reference variable that does not

www. site. uottawa. ca/~elsaddik 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 Null. Pointer. Exception 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 4 (c) elsaddik

www. site. uottawa. ca/~elsaddik The null Reference Class Name. Is. Null { String name;

www. site. uottawa. ca/~elsaddik The null Reference Class Name. Is. Null { String name; // not initialized therefore null Public void print. Name() { System. out. println(name. length()); // this will cause an exception } } 5 (c) elsaddik

www. site. uottawa. ca/~elsaddik The this Reference ØThe this reference allows an object to

www. site. uottawa. ca/~elsaddik 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 == piece 2. 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 6 (c) elsaddik

www. site. uottawa. ca/~elsaddik The this reference ØThe this reference can also distinguish the

www. site. uottawa. ca/~elsaddik 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; acct. Number = account; balance = initial; } 7 (c) elsaddik

www. site. uottawa. ca/~elsaddik The this reference ØThe this reference can also distinguish the

www. site. uottawa. ca/~elsaddik 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 acct. Number, double balance) { this. name = name; this. acct. Number = acct. Number; this. balance = balance; } 8 (c) elsaddik

www. site. uottawa. ca/~elsaddik Assignment Revisited The act of assignment takes a copy of

www. site. uottawa. ca/~elsaddik Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable ØFor primitive types: num 2 = num 1; Before 9 (c) elsaddik After num 1 num 2 5 12 5 5

www. site. uottawa. ca/~elsaddik Reference Assignment For object references, assignment copies the memory location:

www. site. uottawa. ca/~elsaddik Reference Assignment For object references, assignment copies the memory location: bishop 2 = bishop 1; Before bishop 1 10 (c) elsaddik bishop 2 After bishop 1 bishop 2

www. site. uottawa. ca/~elsaddik Aliases ØTwo or more references that refer to the same

www. site. uottawa. ca/~elsaddik 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 11 (c) elsaddik

www. site. uottawa. ca/~elsaddik Testing Objects for Equality ØThe == operator compares object references

www. site. uottawa. ca/~elsaddik 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 bishop 1. equals(bishop 2); returns true if both references refer to the same object 12 (c) elsaddik ØWe can redefine the equals method to return true under whatever conditions we think are appropriate

www. site. uottawa. ca/~elsaddik Garbage Collection ØAll interaction with an object occurs through a

www. site. uottawa. ca/~elsaddik 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 13 (c) elsaddik

www. site. uottawa. ca/~elsaddik Passing Objects as Parameters ØParameters in a Java method are

www. site. uottawa. ca/~elsaddik 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 14 (c) elsaddik

www. site. uottawa. ca/~elsaddik Passing Objects to Methods What you do using a parameter

www. site. uottawa. ca/~elsaddik 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 Parameter. Passing. java (page xxx) See Parameter. Tester. java (page xxx) See Num. java (page xxx) Note the difference between changing the reference and changing the object that the reference points to 15 (c) elsaddik

www. site. uottawa. ca/~elsaddik Parameter. Passing. java public class Parameter. Passing { // sets

www. site. uottawa. ca/~elsaddik Parameter. Passing. java public class Parameter. Passing { // sets up 3 variables and illustrate parameter passing public static void main (String [] args) { Parameter. Tester tester = new Parameter. Tester(); int a 1 = 111; Num a 2 = new Num (222); Num a 3 = new Num (333); System. out. println("Before Change. Values: "); System. out. println("a 1 a 2 a 3: " + a 1 + " " + a 2 + " " + a 3); tester. change. Values(a 1, a 2, a 3); } } 16 (c) elsaddik System. out. println("After Change. Values: "); System. out. println("a 1 a 2 a 3: " + a 1 + " " + a 2 + " " + a 3);

www. site. uottawa. ca/~elsaddik Parameter. Tester. java public class Parameter. Tester { public void

www. site. uottawa. ca/~elsaddik Parameter. Tester. java public class Parameter. Tester { public void change. Values(int f 1, Num f 2, Num f 3) { System. out. println("Before changing the values: "); System. out. println("f 1 f 2 f 3: " + f 1 + " " + f 2 + " " + f 3); f 1 = 999; f 2. set. Value(888); f 3 = new Num(777); System. out. println("After changing the values: "); System. out. println("f 1 f 2 f 3: " + f 1 + " " + f 2 + " " + f 3); } } 17 (c) elsaddik

www. site. uottawa. ca/~elsaddik Num. java public class Num { private int value; //

www. site. uottawa. ca/~elsaddik Num. java public class Num { private int value; // Constructor public Num (int update) { value = update; } // set up a value public void set. Value(int update) { value = update; } // to. String public String to. String() { return value + " "; } 18 (c) elsaddik }

www. site. uottawa. ca/~elsaddik The results: Parameter passing Before Change. Values: a 1 a

www. site. uottawa. ca/~elsaddik The results: Parameter passing Before Change. Values: a 1 a 2 a 3: 111 222 333 Before changing the values: f 1 f 2 f 3: 111 222 333 After changing the values: f 1 f 2 f 3: 999 888 777 After Change. Values: a 1 a 2 a 3: 111 888 333 19 (c) elsaddik

www. site. uottawa. ca/~elsaddik What are Static Variables? ØAssociated with the class rather than

www. site. uottawa. ca/~elsaddik 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 20 (c) elsaddik

www. site. uottawa. ca/~elsaddik What are Static Variables? Can we declare Local Variables as

www. site. uottawa. ca/~elsaddik What are Static Variables? Can we declare Local Variables as static? Can a constant (usually declared through the final modifier) be static? 21 (c) elsaddik

www. site. uottawa. ca/~elsaddik More about Static Methods ØStatic methods (also called class methods)

www. site. uottawa. ca/~elsaddik 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); 22 (c) elsaddik

www. site. uottawa. ca/~elsaddik More about Static Methods: An example class Helper public static

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

www. site. uottawa. ca/~elsaddik Static Methods and Variables: Count. Instances. java public class Count.

www. site. uottawa. ca/~elsaddik Static Methods and Variables: Count. Instances. java public class Count. Instances { 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. get. Count()); } } 24 (c) elsaddik

www. site. uottawa. ca/~elsaddik Static Methods and Variables: Slogan. java public class Slogan {

www. site. uottawa. ca/~elsaddik 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 get. Count() { return count; } } 25 (c) elsaddik

www. site. uottawa. ca/~elsaddik What are Wrapper Classes? 26 (c) elsaddik A wrapper class

www. site. uottawa. ca/~elsaddik What are Wrapper Classes? 26 (c) elsaddik A wrapper class represents a particular primitive type For example Integer age. Obj = 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

www. site. uottawa. ca/~elsaddik Some methods of the Integer class: See p. 287 Integer

www. site. uottawa. ca/~elsaddik Some methods of the Integer class: See p. 287 Integer (int value) // constructor: create a new Integer object byte. Value () double. Value () // Return the value of this integer as the corresponding Primitive Type static int Parse. Int (String str) // returns the int corresponding to the value stores in the string 27 (c) elsaddik static String to. Binary. String (int num) // returns a string representation of the integer in the corresponding base

www. site. uottawa. ca/~elsaddik Java I/O is accomplished using objects that represent streams of

www. site. uottawa. ca/~elsaddik 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 28 (c) elsaddik

www. site. uottawa. ca/~elsaddik Keyboard Input Revisited Input can be read from the keyboard

www. site. uottawa. ca/~elsaddik Keyboard Input Revisited Input can be read from the keyboard without using the Keyboard class and Wrapper Classes See Wages 2. java (page 289): More in Chapter 8 import java. io. *; … Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(System. in)); … String name = in. Readline(); 29 (c) elsaddik int hours = Integer. parse. Int(in. read. Line());

www. site. uottawa. ca/~elsaddik 30 (c) elsaddik String myname = new String (“abed”); String

www. site. uottawa. ca/~elsaddik 30 (c) elsaddik String myname = new String (“abed”); String myname = new String (“abed”) );

www. site. uottawa. ca/~elsaddik Nested Classes ØIn addition to containing data and methods, a

www. site. uottawa. ca/~elsaddik 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 31 (c) elsaddik

www. site. uottawa. ca/~elsaddik Nested Classes ØA nested class produces a separate bytecode file

www. site. uottawa. ca/~elsaddik 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. 32 (c) elsaddik

www. site. uottawa. ca/~elsaddik Inner Classes: A Non-static nested class Ø An inner class

www. site. uottawa. ca/~elsaddik 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 Test. Inner { // create and manipulate an outer object public static void main (String[] args) { Outer out = new Outer(); 33 (c) elsaddik } } System. out. println(out); out. change. Message(); System. out. println(out);

www. site. uottawa. ca/~elsaddik Nested Classes: Outer. java public class Outer { private int

www. site. uottawa. ca/~elsaddik Nested Classes: Outer. java public class Outer { private int num; private Inner in 1, in 2; public Outer() { num = 2365; in 1 = new Inner ("Hello"); in 2 = new Inner ("Hello again"); } public void change. Message() { in 1. message = "Eat desert first"; in 2. message = "Another miracle"; } 34 (c) elsaddik public String to. String() { return in 1 + "n" + in 2; } Continued…

www. site. uottawa. ca/~elsaddik Nested classes: Outer. java // The inner class private class

www. site. uottawa. ca/~elsaddik Nested classes: Outer. java // The inner class private class Inner { public String message; public Inner (String str) { message = str; } public String to. String() { num++; return message + "n. Outer number = " + num; } } 35 (c) elsaddik }

www. site. uottawa. ca/~elsaddik Nested classes: The output Hello ØOuter number = 2366 Hello

www. site. uottawa. ca/~elsaddik Nested classes: The output Hello ØOuter number = 2366 Hello again ØOuter number = 2367 Eat desert first ØOuter number = 2368 Another miracle ØOuter number = 2369 36 (c) elsaddik

www. site. uottawa. ca/~elsaddik Interfaces: Useful for software design interface is a reserved word

www. site. uottawa. ca/~elsaddik Interfaces: Useful for software design interface is a reserved word None of the methods in an interface are given a definition (body) public interface Doable { public void do. This(); public int do. That(); public void do. This 2 (float value, char ch); public boolean do. The. Other (int num); } A semicolon immediately follows each method header 37 (c) elsaddik

www. site. uottawa. ca/~elsaddik Interfaces in Java 38 (c) elsaddik ØA Java interface is

www. site. uottawa. ca/~elsaddik Interfaces in Java 38 (c) elsaddik Ø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

www. site. uottawa. ca/~elsaddik Interfaces: An example public class Can. Do implements Doable {

www. site. uottawa. ca/~elsaddik Interfaces: An example public class Can. Do implements Doable { public void do. This () { // whatever } public void do. That () { // whatever } // etc. } 39 (c) elsaddik implements is a reserved word Each method listed in Doable is given a definition

www. site. uottawa. ca/~elsaddik More about Interfaces 40 (c) elsaddik ØAn interface cannot be

www. site. uottawa. ca/~elsaddik More about Interfaces 40 (c) elsaddik Ø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

www. site. uottawa. ca/~elsaddik Interfaces ØA class that implements an interface can implement other

www. site. uottawa. ca/~elsaddik Interfaces ØA class that implements an interface can implement other methods as well ØA class can implement multiple interfaces class Many. Things implements interface 1, interface 2, interface 3 { // 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 41 (c) elsaddik

www. site. uottawa. ca/~elsaddik More about Interfaces ØThe Java standard class library contains many

www. site. uottawa. ca/~elsaddik More about Interfaces ØThe Java standard class library contains many helpful interfaces ØThe Comparable interface contains an abstract method called compare. To, 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 42 (c) elsaddik

www. site. uottawa. ca/~elsaddik The Comparable Interface ØThe Comparable interface provides a common mechanism

www. site. uottawa. ca/~elsaddik The Comparable Interface ØThe Comparable interface provides a common mechanism for comparing one object to another if (obj 1. compare. To(obj 2) < 0) System. out. println (“obj 1 is less than obj 2”); ØThe result is negative is obj 1 is less that obj 2, 0 if they are equal, and positive if obj 1 is greater than obj 2 43 (c) elsaddik

www. site. uottawa. ca/~elsaddik The Iterator Interface ØThe Iterator interface provides a means of

www. site. uottawa. ca/~elsaddik The Iterator Interface ØThe Iterator interface provides a means of moving through a collection of objects, one at a time ØThe has. Next 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 44 (c) elsaddik

www. site. uottawa. ca/~elsaddik About GUIs and Dialog Boxes 45 (c) elsaddik (Much more

www. site. uottawa. ca/~elsaddik About GUIs and Dialog Boxes 45 (c) elsaddik (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 JOption. Pane that simplifies the creation and use of basic dialog boxes

www. site. uottawa. ca/~elsaddik What is an Dialog Box? A graphical component used to

www. site. uottawa. ca/~elsaddik 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! 46 (c) elsaddik

www. site. uottawa. ca/~elsaddik Events 47 (c) elsaddik ØAn event is an object that

www. site. uottawa. ca/~elsaddik Events 47 (c) elsaddik Ø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

www. site. uottawa. ca/~elsaddik Events and Listeners ØThe Java standard class library contains several

www. site. uottawa. ca/~elsaddik 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 48 (c) elsaddik

www. site. uottawa. ca/~elsaddik About Events and Listeners Event Generator Listener This object may

www. site. uottawa. ca/~elsaddik About Events and Listeners Event Generator Listener This object may generate an event 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 49 (c) elsaddik

www. site. uottawa. ca/~elsaddik Listener Interfaces ØWe can create a listener object by writing

www. site. uottawa. ca/~elsaddik 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 Mouse. Listener 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 50 (c) elsaddik

www. site. uottawa. ca/~elsaddik An event listener: Push. Counter. java (an extract) import java.

www. site. uottawa. ca/~elsaddik An event listener: Push. Counter. java (an extract) import java. awt. *; import java. awt. event. *; import javax. swing. *; public class Push. Counter extends JApplet { private int pushes … This. Add. Action. Listener(new My. Listener()); public void int () { pushes = 0; push = new JButton(“PUSH ME!”); push. Add. Action. Listener(new Button. Listener()); … 51 (c) elsaddik } PUSH ME!

www. site. uottawa. ca/~elsaddik Summary: Enhancing Classes 52 (c) elsaddik Understand what the following

www. site. uottawa. ca/~elsaddik Summary: Enhancing Classes 52 (c) elsaddik 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

www. site. uottawa. ca/~elsaddik Thank You! 53 (c) elsaddik

www. site. uottawa. ca/~elsaddik Thank You! 53 (c) elsaddik