CSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277

Similar documents
Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference

Chapter 5: Enhancing Classes

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

&KDSWHU(QKDQFLQJ&ODVVHV

ECE 122. Engineering Problem Solving with Java

Interfaces. Quick Review of Last Lecture. November 6, Objects instances of classes. Static Class Members. Static Class Members

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

CS1004: Intro to CS in Java, Spring 2005

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

ECE 122. Engineering Problem Solving with Java

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Anatomy of a Class Encapsulation Anatomy of a Method

Objects and Classes -- Introduction

Chapter 6 Introduction to Defining Classes

Lesson 3: Accepting User Input and Using Different Methods for Output

Packages & Random and Math Classes

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Interfaces, Testing, and Layout Managers

We now start exploring some key elements of the Java programming language and ways of performing I/O

BASICS OF GRAPHICAL APPS

Inheritance. Quick Review of Last Lecture. November 12, Passing Arguments. Passing Arguments. Variable Assignment Revisited

A variable is a name for a location in memory A variable must be declared

Graphical Applications

Using Classes and Objects. Chapter

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

JAVA WRAPPER CLASSES

Array. Prepared By - Rifat Shahriyar

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

1 Shyam sir JAVA Notes

Software Development Activities. Establishing the requirements. Software Design. CMPT 126: Lecture 8 Object-Oriented Design

CMPT 126: Lecture 8 Object-Oriented Design

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

ECE 122. Engineering Problem Solving with Java

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

CHAPTER 7 OBJECTS AND CLASSES

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CSC Java Programming, Fall Java Data Types and Control Constructs

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Introduction to Programming Using Java (98-388)

Chapter 4: Writing Classes

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

Full file at

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

CHAPTER 7 OBJECTS AND CLASSES

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

More About Objects and Methods

this keyword (1). this with constructor (2). cisc3120 design and implementation of software applications I spring 2015 lecture # I.

CS180 Recitation. More about Objects and Methods

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

CS 231 Data Structures and Algorithms, Fall 2016

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

CMSC 331 Second Midterm Exam

Data Types and the while Statement

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

CS260 Intro to Java & Android 03.Java Language Basics

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Principles of Computer Science I

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

CSCE3193: Programming Paradigms

Conditionals and Loops

Selected Questions from by Nageshwara Rao

Operators and Expressions

Programming overview

Come & Join Us at VUSTUDENTS.net

INTERFACE WHY INTERFACE

ITI Introduction to Computing II

ANSWER KEY Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

CT 229 Fundamentals of Java Syntax

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Class Libraries and Packages

USING LIBRARY CLASSES

More About Objects and Methods

Selected Java Topics

Lab5. Wooseok Kim

PROGRAMMING FUNDAMENTALS

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Chapter 2: Using Data

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Chapter 4 Introduction to Control Statements

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

CS56 final (E03) W15, Phill Conrad, UC Santa Barbara Wednesday, 03/18/2015. Name: Umail umail.ucsb.edu. Circle one: 4pm 5pm 6pm

Transcription:

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 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 2 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 3 1

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 4 The null Reference Class NameIsNull String name; // not initialized therefore null Public void printname() System.out.println(name.length()); // this will cause an exception 5 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 6 2

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; 7 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; 8 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 num2 num1 num2 5 12 5 5 9 3

Reference Assignment For object references, assignment copies the memory location: bishop2 = bishop1; Before bishop1 bishop2 After bishop1 bishop2 10 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 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 12 We can redefine the equals method to return true under whatever conditions we think are appropriate 4

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 13 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 14 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 15 5

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); 16 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); 17 Num.java 18 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 + " "; 6

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 19 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 What are Static Variables? Can we declare Local Variables as static? Can a constant (usually declared through the final modifier) be static? 21 7

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 22 public static int abs(int num); 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 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 ()); 24 8

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; 25 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 26 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 27 static String tobinarystring (int num) // returns a string representation of the integer in the corresponding base 9

Java I/O Java I/O is accomplished using objects that represent streams of data A streamis 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 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(); 29 int hours = Integer.parseInt(in.readLine()); String myname = new String ( abed ); String myname = new String ( new String ( abed ) ); 30 10

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 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 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(); 33 System.out.println(out); out.changemessage(); System.out.println(out); 11

Nested Classes: Outer.java 34 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; 35 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 12

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 dothis(); public int dothat(); public void dothis2 (float value, char ch); public boolean dotheother (int num); A semicolon immediately follows each method header 37 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 38 Interfaces: An example public class CanDo implements Doable public void dothis () // whatever implements is a reserved word public void dothat () // whatever Each method listed in Doable is given a definition // etc. 39 13

More about Interfaces 40 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 41 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 42 14

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 43 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 44 About GUIs and Dialog Boxes 45 (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 15

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 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 47 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 48 16

About Events and Listeners Generator Event 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 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 50 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()); 51 public void int () pushes = 0; push = new JButton( PUSH ME! ); push.addactionlistener(new ButtonListener()); PUSH ME! 17

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 52 Thank You! 53 18