CMPT 126: Lecture 8 Object-Oriented Design

Size: px
Start display at page:

Download "CMPT 126: Lecture 8 Object-Oriented Design"

Transcription

1 CMPT 126: Lecture 8 Object-Oriented Design Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University November 13,

2 Software Development Activities When the code for your programs starts getting big, with numerous.java files, you will have to start thinking about how to manage it all. Software development effort consists of four basic development activities 1. establishing the requirements: 2. creating a design 3. implementing the design 4. testing CMPT 126: Object-Oriented Design, Lecture 8 2

3 Establishing the requirements Software requirements: a clear expression of the programming problem specification of what a program must accomplish often using a document called functional specification. usually specified by a client, though often modified throughout the project in conjunction with the programmer often address user interface issues: output format, screen layouts, GUI components, etc. may apply constraints to your program (such as computer resources) CMPT 126: Object-Oriented Design, Lecture 8 3

4 Software Design A software design: indicates how a program will accomplish its requirements. may deal with how methods accomplish their tasks (in a low-level design) allows alternatives to be considered and explored (before all the effort goes into implementation). In an object orientated design, the following is specified: the classes and objects needed in a program the interaction of the objects and the relationships among the classes CMPT 126: Object-Oriented Design, Lecture 8 4

5 Implementation Implementation is the process of writing the source code that will solve the problem. More precisely: the act of translating the design into a programming language should be the least creative of all development activities important decisions are already established CMPT 126: Object-Oriented Design, Lecture 8 5

6 Testing Finding the bugs! Testing is the act of ensuring that a program solves the problem successfully, given all the established constraints. Among other things, it involves running the program several times under several different conditions, and then scrutinizing the results. CMPT 126: Object-Oriented Design, Lecture 8 6

7 Identifying Classes and Objects A fundamental part of object-oriented software design is determining the classes that will contribute to the program. These classes determine the objects that we will manage in the system. To identify potential classes, identify objects discussed in the program requirements. CMPT 126: Object-Oriented Design, Lecture 8 7

8 Look for Nouns in Problem Description Objects are generally nouns; the nouns in a problem description may indicate some of the classes and objects needed in a program. Consider the following excerpt: The user must be allowed to specify each product by its primary characteristics, including its name and product number. If the bar code does not match the product, then an error should be generated to the message window and entered into the error log. The summary report of all transactions must be structured as specified in section 7.A. CMPT 126: Object-Oriented Design, Lecture 8 8

9 Nouns may lead to Objects These nouns will help you think about what types of objects a program will manage. The user must be allowed to specify each product by its primary characteristics, including its name and product number. If the bar code does not match the product, then an error should be generated to the message window and entered into the error log. The summary report of all transactions must be structured as specified in section 7.A. CMPT 126: Object-Oriented Design, Lecture 8 9

10 Class or Object A class represents a group of objects with similar behaviour. A plural noun specification, such as products, may indicate the need for a class such as Product. Even if there is only one of a particular object needed in your system, it may be best represented as a class. Classes that represent objects, should generally be given names that are singular nouns (such as Product). A class represents a single item from which we are free to create as many instances, or objects as we choose. CMPT 126: Object-Oriented Design, Lecture 8 10

11 Object or Primitive Attribute of another Object Depending the program requirement, some objects might be best represented using a primitive data type. If you with to store more information, for example, you may want to create a class. Should a salary be represented using a numeric primitive data type? In addition to the actual salary amount, we may want to represent the employee s rank, and corresponding upper and lower salary bounds. In this case will need to represent the data using a class. CMPT 126: Object-Oriented Design, Lecture 8 11

12 General and Specific Classes Consider a program, perhaps one that is determining our overall daily energy use, which must represent each appliance in our home. Is it necessary to create a separate class for each type of appliance? Might it be better to have a single Appliance class, with instance data indication its type? This will depend on which characteristics of the appliance are important to the class. The traits we may care about: number of hours used per day wattage (maximum power drawn) actual power drawn (stereos, and heaters don t always operate at maximum wattage) We may also be interested in the size and shape of the appliance, so we can determine whether or not it will fit in our Vancouver condo with limited square footage! CMPT 126: Object-Oriented Design, Lecture 8 12

13 Other Management Classes In addition to the classes that represent the objects from the problem description, we will need classes that support the work necessary to accomplish the tasks. Examples: In addition to Member objects, we may want a separate class to help us manage all the members of a club. Recall our linked list implementation: we had a class for each Node, and then a class for managing the Nodes in the form of a list. CMPT 126: Object-Oriented Design, Lecture 8 13

14 Reusing Existing Classes We may not have to design everything from scratch! Classes may already exists, that may be similar enough to be used as the basis for our new class. The existing code may be part of the Java standard library, our own previously developed code, or part of a library made available through a third party. We can use these classes as is, or create new classes by extending these existing classes (more on inheritance later). CMPT 126: Object-Oriented Design, Lecture 8 14

15 Assigning Responsibilities Any activity that the program must accomplish must be represented somewhere in the behaviours of the classes. Part of the identifying classes needed, is the process of assigning responsibilities to each class. Each class represents an object with certain behaviours that are defined by the methods of the class. Assigning responsibilities to the classes is part of the program design. CMPT 126: Object-Oriented Design, Lecture 8 15

16 Static Class Members A static method is one that is invoked through its class name, instead of through an object of that class. Both methods and variables can be static (declared using the static modifier). When should a method or variable be declared static? constants helper methods no need to maintain results of past computations CMPT 126: Object-Oriented Design, Lecture 8 16

17 Static Variables So far we ve seen two types of variables: 1. local variables: declared inside a method. 2. instance variables: declared in a class (but outside of a method), with each instance of a class having its own distinct memory space for each instance variable. A static variable, sometimes called a class variable, is share among all instances of a class. Memory for a static variable is established when the class that contains it is reference for the first time in a program. Local variables (declared within a method) cannot be static. Constants, declared using the final modifier, are often declared as static; since their value cannot be changed, one copy for all objects of the class usually suffices. CMPT 126: Object-Oriented Design, Lecture 8 17

18 Static Methods Static methods can be invoked through the class name (recall the methods in the Math class are static. System.out.println( Square root of 27: + Math.sqrt(27)); In the case of the Math class, there is no need to maintain parameters or values of past computations. There is therefore, not need to create an object. The main method of a Java program is declared static so that if can be executed by the interpreter without instantiating the class that contains main. CMPT 126: Object-Oriented Design, Lecture 8 18

19 Still to Consider... Since static methods do not operate within the context of a particular object, they cannot reference instance variables (compile-time error). A static method can, however, reference static variables. The main method can therefore access only static or local variables. CMPT 126: Object-Oriented Design, Lecture 8 19

20 Example Use of a Static Variable Suppose your program required a number of slogans. Would you store using a String? or would you create a new class? Though a slogan is essentially a phrase, if you made it a class you could also have a static variable that counted the number of objects created. A count variable can be incremented each time classes constructor is called (something which happens only upon instantiation). CMPT 126: Object-Oriented Design, Lecture 8 20

21 Slogan.java public class Slogan private String phrase; private static int count = 0; //Constructor: Sets up slogan and counts instances. public Slogan (String str) phrase = str; count++; public String tostring() return phrase; public static int getcount() return count; public class SloganCounter public static void main(string[] args) Slogan obj = new Slogan("You can lead a horse..."); System.out.println("Slogans created: " + Slogan.getCount()); CMPT 126: Object-Oriented Design, Lecture 8 21

22 Slogan Class The constructor of the slogan class increments a static variable called count (which is initialized to zero when it is declared). The variable count keeps track of the number of instances of Slogan that are created. A method called getcount, returns the number of Slogan objects that are instantiated. The method getcount is static, allowing it to be invoked through the class name rather than through an instance of the class. The method getcount can reference the count variable because it too is static. CMPT 126: Object-Oriented Design, Lecture 8 22

23 Class Relationships Three types of relationships between classes in a software include 1. dependency: one class uses another 2. aggregation: the objects of one class contain objects of another ( has a relationship) 3. inheritance: is a relationship (to be discussed in more detail next lecture). CMPT 126: Object-Oriented Design, Lecture 8 23

24 Dependency One class relies on another class in some sense. Establishes a uses relationship. Often the methods of one class A will invoke or use the methods of the other class B. If an invoked method is static, then A merely references B by name. Otherwise, A must have access to a specific instance of class B. CMPT 126: Object-Oriented Design, Lecture 8 24

25 Object Access and Design The way in which one object gains access to an object of another class is an important design decision. When one class instantiates the objects of another, it s often an aggregation ( has a ) relationship. Access can also be accomplished by passing one object to another as a method parameter. In general, we want to minimized the number of dependencies among classes so that changes will have less impact on the entire design. CMPT 126: Object-Oriented Design, Lecture 8 25

26 Dependency Among Objects of the Same Class In some cases, objects of the same class will interact with each other. This can be accomplished by having a method of the class accept as a parameter an object of them same class. Example: the concat method of the String class. The method is executed through one String object, and is passed another String object: str3 = str1.concat(str2); Also, the Node class from the linked list had a reference to itself. The RationalTester (next slide) also shows the dependency of a class on itself. CMPT 126: Object-Oriented Design, Lecture 8 26

27 RationalNumer.java public class RationalNumber private int numerator, denominator; public RationalNumber(int num, int den) if (den == 0) den = 1; // Make num "store" the sign if (den < 0) num = num * -1; den = den * -1; numerator = num; denominator = den; reduce(); public int getnumerator() return numerator; public int getdenominator() return denominator; public RationalNumber reciprocal() return new RationalNumber(denominator, numerator); CMPT 126: Object-Oriented Design, Lecture 8 27

28 public RationalNumber add(rationalnumber op2) int commondenominator = denominator * op2.getdenominator(); int num1 = numerator * op2.getdenominator(); int num2 = op2.getnumerator() * denominator; int sum = num1 + num2; return new RationalNumber(sum, commondenominator); public RationalNumber subtract(rationalnumber op2) int commondenominator = denominator * op2.getdenominator(); int num1 = numerator * op2.getdenominator(); int num2 = op2.getnumerator() * denominator; int diff = num1 - num2; return new RationalNumber(diff, commondenominator); public RationalNumber multiply(rationalnumber op2) int num = numerator * op2.getnumerator(); int den = denominator * op2.getdenominator(); return new RationalNumber(num, den); public RationalNumber divide(rationalnumber op2) return multiply(op2.reciprocal()); // Assumes both are reduced public boolean equals(rationalnumber op2) return(numerator == op2.getnumerator() && denominator == op2.getdenominator() ); CMPT 126: Object-Oriented Design, Lecture 8 28

29 public String tostring() String result; if (numerator == 0) result = "0"; else if (denominator == 1) result = numerator + ""; else result = numerator + "/" + denominator; return result; private void reduce() if (numerator!= 0) int common = gcd(math.abs(numerator), denominator); numerator = numerator / common; denominator = denominator / common; private int gcd(int num1, int num2) while (num1!= num2) if (num1 > num2) num1 = num1 - num2; else num2 = num2 - num1; return num1; CMPT 126: Object-Oriented Design, Lecture 8 29

30 Aggregation An aggregate object is composed of other objects, forming a has a relationship. Examples: A car is composed of its engine, its chassis, its wheels, and other parts. The car is, therefore, an aggregation. An object of type Account has a String object that represents the name of the account holder. The Account object is, therefore, an aggregate object. An aggregate object is one that contains references to other objects as instance data. Methods from the aggregate object generally invoke methods of the object from which it is composed. The more complex an object, the more likely it will need to be represented as an aggregate object. CMPT 126: Object-Oriented Design, Lecture 8 30

31 A UML Class Diagram StudentBody demonstrates the use of an aggregate class. Aggregation is represented by a connection between two classes, with an open diamond at the end connected to the aggregate. StudentBody +main(args : String[]) : void Student firstname : String lastname : String homeaddress : Address schooladdress : Address + tostring() : String Address streetaddress : String city : String state : String zipcode : long + tostring() : String Figure 1: A UML class diagram showing aggregation CMPT 126: Object-Oriented Design, Lecture 8 31

32 The this Reference The word this is a reserved word allowing an object to refer to itself. When a nonstatic method is invoked by an object, the this reference can be used to refer to the current, executing, object. Example: In a the class ChessPiece, a method called move contains the following line: if (this.position == piece2.position) result = false; When the move method is invoked by the following line: bishop1.move() the reference this is being used to specify of position of bishop1. CMPT 126: Object-Oriented Design, Lecture 8 32

33 Using this to Distinguish Variables this is also used to distinguish the parameters of a constructor from their corresponding instance variables with the same names: public Account(String owner, long acctnum) name = owner; account = acctnum; OR alternatively public Account(String name, long account) this.name = name; this.account = account; This eliminates the need to come up with different, yet equivalent, names. CMPT 126: Object-Oriented Design, Lecture 8 33

34 Interfaces and Abstract Methods We previously used the term interface to refer to the set of public methods through which we can interact with an object. A Java interface is a collection of constants and abstract methods. public interface Complexity public void setcomplexity(int complexity); public int getcomplexity(); An abstract method is one which is declared but which does not have an implementation. It can be preceded by the word abstract, though in interfaces it usually isn t. In addition to, or instead of, abstract methods, an interface can contain constants (defined using the final modifier). CMPT 126: Object-Oriented Design, Lecture 8 34

35 Using an Interface An interface cannot be instantiated. Rather, an interface defines how to interact with a class by guaranteeing the class will implement certain methods. If a class implements an interface therefore, it must provide a definition (implementation) for each of its abstract methods (or the compiler will complain). The class that implements an interface is not restricted from having additional methods. A class can implement more than one interface. CMPT 126: Object-Oriented Design, Lecture 8 35

36 A class implements an interface Another reserved word in Java is implements: public class Question implements Complexity The Question class implements the Complexity, interface, and therefore provides implementation for the methods: public void setcomplexity(int Complexity); public int getcomplexity(); CMPT 126: Object-Oriented Design, Lecture 8 36

37 Question.java public class Question implements Complexity private String question, answer; private int complexitylevel; public Question(String query, String result) question = query; answer = result; complexitylevel = 1; public void setcomplexity(int level) complexitylevel = level; public int getcomplexity() return complexitylevel; public String getquestion() return question; public String getanswer() return answer; public boolean answercorrect(string candidateanswer) return answer.equals(candidateanswer); public String tostring() return question + "\n" + answer; CMPT 126: Object-Oriented Design, Lecture 8 37

38 MiniQuiz.java import java.util.scanner; public class MiniQuiz public static void main(string[] args) Question q1, q2; String possible; Scanner scan = new Scanner(System.in); q1 = new Question("What is the capital of Jamaica? ", "Kingston"); q1.setcomplexity(4); System.out.print(q1.getQuestion()); System.out.println("(Level: " + q1.getcomplexity() + ")"); possible = scan.nextline(); if (q1.answercorrect(possible)) System.out.println("Correct"); else System.out.println("No, the answer if " + q1.getanswer()); CMPT 126: Object-Oriented Design, Lecture 8 38

39 UML Class Diagram for MiniQuiz <<interface>> Complexity MiniQuiz + getcomplexity() : int + setcomplexity(int) : void +main(args : String[]) : void Question + getquestion() : String + getanswer() : String + answercorrect(string) : boolean + tostring() : String Figure 2: A UML class diagram for the MiniQuiz program. CMPT 126: Object-Oriented Design, Lecture 8 39

40 The Comparable Interface The Comparable interface is in the Java standard library (java.lang package). It contains only one method: compareto, taking an object as a parameter and returning an integer. It provides a common mechanism for comparing objects if (obj1.compareto(obj2) < 0) System.out.println("obj1 is less than obj2); The interface returns a positive number if obj1 > obj2 0 if obj1 == obj2 negative number obj1 < obj2 It is up to the designer to determine the actual meaning of the comparison. Notice that the String class has a compareto method because it implements the Comparable interface. CMPT 126: Object-Oriented Design, Lecture 8 40

41 The Iterator Interface Defined in the Java standard library. It is used by collection classes, for iterating through each object. Three of its methods are: hasnext: returns a boolean, the value of which depends on whether there are any remaining objects next: returns the next object. remove: removes the object that was most recently returned by the next method. Book mybook; while (BookList.hasNext()) mybook = BookList.next(); System.out.println (mybook); Or equivalently, for(book mybook : BookList) System.out.println(myBook); CMPT 126: Object-Oriented Design, Lecture 8 41

42 Revisiting Enumerated Types Recall, an enumerated type is special kind of class, and values of an enumerated type are objects. enum Seasonwinter, spring, summer, fall The values of an enumerated type are instances of its own enumerated type: winter is an object of the Season class. Example: In Season time; time is an object reference variable that can be assigned only those values in the Season definition: winter, spring, summer, and fall. It cannot be instantiated. These values are references to Season objects that are stored as public static variables within the Season class. time = Season.spring; We do not need to (nor can we) instantiate Season; CMPT 126: Object-Oriented Design, Lecture 8 42

43 Season enum Class Since Season is a class, we can add attributes and methods to the definition of an enumerated type. public enum Season winter("december through February"), //note comma spring("march through May"), summer("june through August"), fall("september through November"); //note semicolon private String span; // Constructor: sets up associated string Season(String months) span = months; public String getspan() return span; CMPT 126: Object-Oriented Design, Lecture 8 43

44 SeasonTester.java public class SeasonTester public static void main (String[] args) for (Season time : Season.values()) System.out.println(time + "\t" + time.getspan()); OUTPUT: winter December through February spring March through May summer June through August fall September through November CMPT 126: Object-Oriented Design, Lecture 8 44

45 Method Design Algorithm An algorithm is a step-by-step process for solving a problem. Every method implements an algorithm, allowing the method to accomplish its goals. An algorithm may first be designed in pseudocode, an english friendly solution to the problem, independent of any programming language syntax. Here, we discuss two method design aspects: 1. Method decomposition 2. Objects as method parameters CMPT 126: Object-Oriented Design, Lecture 8 45

46 Method Decomposition An algorithm may be too complex for a a single method, and therefore may need to be decomposed into multiple methods. Consider the task of translating a sentence into Pig Latin. How might we design a (or several) method(s)? Problem description: Pig Latin is a made-up language in which each word of a sentence is modified by moving the initial sound (a consonant or a blend: sh ch ) to the end and adding an ay sound. Eg: happy becomes appyhay. Words that begin with vowels simply have a yay sound added on the end. Eg: enough becomes enoughyay. CMPT 126: Object-Oriented Design, Lecture 8 46

47 Translating to Pig Latin Translating into Pig Latin is too big a task for a single method. The translate method uses the Scanner class to separate the string into words (or more specifically tokens separated by spaces characters), assuming no punctuation. The translate method passes each word to the translateword method which in turn uses the beginswithvowel and beginswithblend. All methods except translate are declared private, and made invisible outside the class. CMPT 126: Object-Oriented Design, Lecture 8 47

48 Pig Latin Translator public class PigLatinTranslator public static String translate(string sentence) String result = ""; sentence = sentence.tolowercase(); Scanner scan = new Scanner(sentence); while(scan.hasnext()) result += translateword(scan.next()); result += " "; return result; private static String translateword(string word) String result = ""; if (beginswithvowel(word)) result = word + "yay"; else if (beginswithblend(word)) result = word.substring(2) + word.substring(0,2) + "ay"; else result = word.substring(1) + word.charat(0) + "ay"; return result; CMPT 126: Object-Oriented Design, Lecture 8 48

49 private static boolean beginswithvowel(string word) String vowels = "aeiou"; char letter = word.charat(0); return(vowels.indexof(letter)!= -1); private static boolean beginswithblend(string word) return(word.startswith("bl") word.startswith("sc") word.startswith("br") word.startswith("sh") word.startswith("ch") word.startswith("sk") word.startswith("cl") word.startswith("sl") word.startswith("cr") word.startswith("sn") word.startswith("dr") word.startswith("sm") word.startswith("dw") word.startswith("sp") word.startswith("fl") word.startswith("sq") word.startswith("fr") word.startswith("st") word.startswith("gl") word.startswith("sw") word.startswith("gr") word.startswith("th") word.startswith("kl") word.startswith("tr") word.startswith("ph") word.startswith("tw") word.startswith("pl") word.startswith("wh") word.startswith("pr") word.startswith("wr") ); CMPT 126: Object-Oriented Design, Lecture 8 49

50 References revisited Unlike a variable that is a primitive data type (which stores an actual value), every object variable is a reference to an object. Assignments, copy only the object reference. If the purpose is to have two separate versions of an object, the clone() method should be used instead. If there are several variables holding references to the same object, it may be difficult to track any changes being made. CMPT 126: Object-Oriented Design, Lecture 8 50

51 Method Parameters Revisited In Java, all parameters are passed into methods by value. Passing a parameter is akin to an assignment statement. When making a change to a formal parameter inside a method, the changes will have no effect on the actual parameter since the formal parameter is a separate copy of the value passed in. However, when we pass an object to a method, we are actually passing a reference to that object. That is, the value that gets copied is the address of the object. The formal and actual parameters are aliases and a change of the the former will change the latter (unless we change the object being referenced by the formal parameter. CMPT 126: Object-Oriented Design, Lecture 8 51

52 ParameterModifier public class ParameterModifier public void changevalues(int f1, Num f2, Num f3) // print values before changing... f1 = 999; f2.setvalue(888); f3 = new Num(777); // print values after changing... public class ParameterTester public static void main(string[] args) ParameterModifier modifier = new ParameterModifier(); int a1 = 111; Num a2 = new Num(222); Num a3 = new Num(333); System.out.println("Before calling changevalues:"); System.out.println("a1\ta2\ta3"); System.out.println(a1 + "\t" + a2 + "\t" + a3 + "\n"); modifier.changevalues(a1,a2,a3); System.out.println("After calling changevalues:"); System.out.println("a1\ta2\ta3"); System.out.println(a1 + "\t" + a2 + "\t" + a3 + "\n"); CMPT 126: Object-Oriented Design, Lecture 8 52

53 Immutable Objects An immutable object is one whose state cannot be modified after it is created. If an object is immutable, it is sufficient to copy a reference rather than the entire object. Imutability is a compile-time construct, dictating how the programmer must handle the object; it does not imply that the object s memory is unwritable. Example: String s = ABC ; // s.tolower(); In this example, data is not changed; rather, a new string is created and returned. CMPT 126: Object-Oriented Design, Lecture 8 53

54 Method Overloading Often a method name is sufficient in indicating which method is called by a method invocation. You can however, have methods with the same name but which have a different parameter list. This is called method overloading. In this case it is the parameter lists that distinguishes between methods, and determines which one will be invoked. Distinguishing characteristics include: a different number of parameters, parameters of different types, and/or in a different order. public int sum(int num1, int num2) return num1+num2; public int sum(int num1, int num2, int num3) return num1+num2+num3; CMPT 126: Object-Oriented Design, Lecture 8 54

55 Method Signature A method s name, along with the number, type, and order of its parameters, is called the method s signature. The compiler chooses the appropriate method based on the signature. NOTE: The return type is not part of the signature and is not enough to distinguish two overloaded methods (since a return value can be ignored by an invocation). A partial signature list for the println method includes: println(string s) println(int i) println(double d) println(char c) println(boolean b) CMPT 126: Object-Oriented Design, Lecture 8 55

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

Software Development Activities. Establishing the requirements. Software Design. CMPT 126: Lecture 8 Object-Oriented Design Software Development Activities CMPT 126: Lecture 8 Object-Oriented Design Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University November 13, 2007 When the code for your

More information

Object-Oriented Design. Chapter. Class Relationships. Classes in a software system can have various types of relationships to each other

Object-Oriented Design. Chapter. Class Relationships. Classes in a software system can have various types of relationships to each other Object-Oriented Design 6 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Class Relationships Classes in a software

More information

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

Interfaces. Quick Review of Last Lecture. November 6, Objects instances of classes. Static Class Members. Static Class Members November 6, 2006 Quick Review of Last Lecture ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev Objects instances of a class with a static variable size

More information

Object-Oriented Design. Chapter

Object-Oriented Design. Chapter Object-Oriented Design 6 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Outline Software Development Activities

More information

Writing Classes Chapter 5. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Writing Classes Chapter 5. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Writing Classes Chapter 5 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Writing your own Classes and Methods: Data Flow Diagrams and Structured Analysis Identifying classes

More information

Program Development. These activities are not strictly linear they overlap and interact

Program Development. These activities are not strictly linear they overlap and interact Review (cont.) Program Development The creation of software involves four basic activities: establishing the requirements creating a design implementing the code testing the implementation These activities

More information

Chapter 7 Object-Oriented Design

Chapter 7 Object-Oriented Design Chapter 7 Object-Oriented Design Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus Object-Oriented Design Now we can extend our discussion of the design of

More information

CS101 Class Notes April 25-25, Taygun Murat Yilmaz CHAPTER 6; Static Variables, Class Dependency, Class Aggregation, Interfaces

CS101 Class Notes April 25-25, Taygun Murat Yilmaz CHAPTER 6; Static Variables, Class Dependency, Class Aggregation, Interfaces CS101 Class Notes April 25-25, 2007-05-24 Taygun Murat Yilmaz CHAPTER 6; Static Variables, Class Dependency, Class Aggregation, Interfaces Relationships among classes: Inheritance Aggregation Dependency

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #23: OO Design, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia HW#5 due Tuesday And if you re cheating on (or letting others see your) HW#5

More information

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

Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference CSI1102: Introduction to Software Design Chapter 5: Enhancing Classes Learning objectives: Enhancing Classes Understand what the following entails Different object references and aliases Passing objects

More information

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS BİLGE KÖROĞLU Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS Method Decomposition: Every method should be understandable therefore sometimes wee need to decompose some methods into smaller

More information

Interfaces, Testing, and Layout Managers

Interfaces, Testing, and Layout Managers Interfaces, Testing, and Layout Managers Alark Joshi Identifying Classes and Objects The core activity of object-oriented design is determining the classes and objects that will make up the solution The

More information

CMPT 125: Lecture 4 Conditionals and Loops

CMPT 125: Lecture 4 Conditionals and Loops CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed

More information

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

CSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277 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/

More information

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

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others COMP-202 Objects, Part III Lecture Outline Static Member Variables Parameter Passing Scopes Encapsulation Overloaded Methods Foundations of Object-Orientation 2 Static Member Variables So far, member variables

More information

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

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 - Week 7 1 Static member variables So far: Member variables

More information

Building Your Own Classes

Building Your Own Classes COMP-202 Building Your Own Classes Lecture Outline Anatomy of a Class Methods Method Kinds Method Signature Method Invocation Method Body Parameter Passing The Bank Application Example Instance Data public

More information

Chapter 5: Writing Classes and Enums

Chapter 5: Writing Classes and Enums Chapter 5: Writing Classes and Enums CS 121 Department of Computer Science College of Engineering Boise State University August 22, 2016 Chapter 5: Writing Classes and Enums CS 121 1 / 48 Chapter 5 Topics

More information

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) COMP 202 Objects 2 1

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) COMP 202 Objects 2 1 COMP 202 Building Your Own Classes CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) COMP 202 Objects 2 1 COMP 202 We've been using predefined classes. Now we will learn to write

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 15 Class Relationships Outline Problem: How can I create and store complex objects? Review of static methods Consider static variables What about objects

More information

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) Instance Data. COMP Objects 2 1

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) Instance Data. COMP Objects 2 1 COMP 202 Building Your Own Classes CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) Instance Data COMP 202 - Objects 2 1 COMP 202 We've been using predefined classes. Now we will

More information

writing classes objectives chapter

writing classes objectives chapter 4 chapter objectives Define classes that serve as blueprints for new objects, composed of variables and methods. Explain the advantages of encapsulation and the use of Java modifiers to accomplish it.

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

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

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 Objects 3 1 Static member variables So far: Member variables

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 21 Interfaces and Abstract Classes Overview Problem: Can we make inheritance flexible? Abstract methods Define methods that will be filled in by children

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 5 Anatomy of a Class Outline Problem: How do I build and use a class? Need to understand constructors A few more tools to add to our toolbox Formatting

More information

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Things to Review Review the Class Slides: Key Things to Take Away Do you understand

More information

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 4: Writing Classes Objects An object has: Presentation slides for state - descriptive characteristics Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus,

More information

Chapter 5: Enhancing Classes

Chapter 5: Enhancing Classes Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by

More information

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

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published

More information

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

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

More information

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods Encapsulation You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods external - the interaction of the object with other objects in the program

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a

More information

Objects and Classes -- Introduction

Objects and Classes -- Introduction Objects and Classes -- Introduction Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes

More information

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1 UNIVERSITY OF EAST ANGLIA School of Computing Sciences Main Series UG Examination 2017-18 PROGRAMMING 1 CMP-4008Y Time allowed: 2 hours Answer FOUR questions. All questions carry equal weight. Notes are

More information

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination November 7th, 2012 Examiners: Daniel Pomerantz [Sections

More information

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes 1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist

More information

Anatomy of a Class Encapsulation Anatomy of a Method

Anatomy of a Class Encapsulation Anatomy of a Method Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing

More information

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

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables Java Program Structure // comments about the class public class MyProgram { Java Review class header class body Comments can be placed almost anywhere This class is written in a file named: MyProgram.java

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

More About Objects and Methods

More About Objects and Methods More About Objects and Methods Chapter 6 Objectives Define and use constructors Write and use static variables and methods Use methods from class Math Use predefined wrapper classes Use stubs, drivers

More information

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6 Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Creating

More information

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course : Advanced Java Concepts + Additional Questions from Earlier Parts of the Course 1. Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... In what order

More information

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA

More information

Chapter 1b Classes and Objects

Chapter 1b Classes and Objects Data Structures for Java William H. Ford William R. Topp Chapter 1b Classes and Objects Bret Ford 2005, Prentice Hall Object-Oriented Programming An object is an entity with data and operations on the

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Packages & Random and Math Classes

Packages & Random and Math Classes Packages & Random and Math Classes Quick review of last lecture September 6, 2006 ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev Objects Classes An object

More information

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination Thursday, March 11, 2010 Examiners: Milena Scaccia

More information

Java Flow of Control

Java Flow of Control Java Flow of Control SEEM 3460 1 Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming statements

More information

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

BM214E Object Oriented Programming Lecture 8

BM214E Object Oriented Programming Lecture 8 BM214E Object Oriented Programming Lecture 8 Instance vs. Class Declarations Instance vs. Class Declarations Don t be fooled. Just because a variable might be declared as a field within a class that does

More information

Chapter 4: Writing Classes

Chapter 4: Writing Classes Chapter 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Writing Classes We've been using predefined classes. Now we will learn to write our own

More information

CSE 403: Software Engineering, Spring courses.cs.washington.edu/courses/cse403/15sp/ UML Class Diagrams. Emina Torlak

CSE 403: Software Engineering, Spring courses.cs.washington.edu/courses/cse403/15sp/ UML Class Diagrams. Emina Torlak CSE 403: Software Engineering, Spring 2015 courses.cs.washington.edu/courses/cse403/15sp/ UML Class Diagrams Emina Torlak emina@cs.washington.edu Outline Designing classes Overview of UML UML class diagrams

More information

Formatting Output & Enumerated Types & Wrapper Classes

Formatting Output & Enumerated Types & Wrapper Classes Formatting Output & Enumerated Types & Wrapper Classes Quick review of last lecture September 8, 2006 ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev

More information

PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write

More information

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

Objectives of CS 230. Java portability. Why ADTs?  8/18/14 http://cs.wellesley.edu/~cs230 Objectives of CS 230 Teach main ideas of programming Data abstraction Modularity Performance analysis Basic abstract data types (ADTs) Make you a more competent programmer

More information

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination Tuesday, November 3, 2009 Examiners: Mathieu Petitpas

More information

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

Inheritance. Quick Review of Last Lecture. November 12, Passing Arguments. Passing Arguments. Variable Assignment Revisited Inheritance November 12, 200 Quick Review of Last Lecture ComS 20: Programming I (in Java) Iowa State University, FALL 200 Instructor: Alexander Stoytchev Passing Arguments Another important issue related

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

CompSci 125 Lecture 11

CompSci 125 Lecture 11 CompSci 125 Lecture 11 switch case The? conditional operator do while for Announcements hw5 Due 10/4 p2 Due 10/5 switch case! The switch case Statement Consider a simple four-function calculator 16 buttons:

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Topic 5: Enumerated Types and Switch Statements

Topic 5: Enumerated Types and Switch Statements Topic 5: Enumerated Types and Switch Statements Reading: JBD Sections 6.1, 6.2, 3.9 1 What's wrong with this code? if (pressure > 85.0) excesspressure = pressure - 85.0; else safetymargin = 85.0 - pressure;!

More information

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

Use the scantron sheet to enter the answer to questions (pages 1-6)

Use the scantron sheet to enter the answer to questions (pages 1-6) Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object

More information

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x? x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x? x++ vs. ++x public class Plus{ public static void main(string []args){ int x=0; int a=++x; System.out.println(x); System.out.println(a);

More information

Java Foundations Certified Junior Associate

Java Foundations Certified Junior Associate Java Foundations Certified Junior Associate 习题 1. When the program runs normally (when not in debug mode), which statement is true about breakpoints? Breakpoints will stop program execution at the last

More information

HST 952. Computing for Biomedical Scientists Lecture 5

HST 952. Computing for Biomedical Scientists Lecture 5 Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 5 Outline Recursion and iteration Imperative and

More information

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

COMP 250 Winter 2011 Reading: Java background January 5, 2011 Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP

More information

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination Thursday, December 11, 2008 Examiners: Mathieu Petitpas [Section 1] 14:00

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a Spring 2017 Name: TUID: Page Points Score 1 28 2 18 3 12 4 12 5 15 6 15 Total: 100 Instructions The exam is closed book, closed notes. You may not use a calculator, cell phone, etc. i Some API Reminders

More information

Conditionals and Loops

Conditionals and Loops Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional

More information

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects Administrative Stuff September 12, 2007 HW3 is due on Friday No new HW will be out this week Next Tuesday we will have Midterm 1: Sep 18 @ 6:30 7:45pm. Location: Curtiss Hall 127 (classroom) On Monday

More information

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

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

CS 116. Lab Assignment # 1 1

CS 116. Lab Assignment # 1 1 Points: 2 Submission CS 116 Lab Assignment # 1 1 o Deadline: Friday 02/05 11:59 PM o Submit on Blackboard under assignment Lab1. Please make sure that you click the Submit button and not just Save. Late

More information

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill CSCI 136 Data Structures & Advanced Programming Lecture 3 Fall 2018 Instructors: Bill & Bill Administrative Details Lab today in TCL 217a (and 216) Lab is due by 11pm Sunday Lab 1 design doc is due at

More information

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017 Java Methods Lecture 8 COP 3252 Summer 2017 May 23, 2017 Java Methods In Java, the word method refers to the same kind of thing that the word function is used for in other languages. Specifically, a method

More information

Faculty of Science COMP-202A - Foundations of Computing (Fall 2013) - All Sections Midterm Examination

Faculty of Science COMP-202A - Foundations of Computing (Fall 2013) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Foundations of Computing (Fall 2013) - All Sections Midterm Examination November 11th, 2013 Examiners: Jonathan Tremblay [Sections

More information

CMPT 126: Lecture 6 Arrays

CMPT 126: Lecture 6 Arrays CMPT 126: Lecture 6 Arrays Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University September 25, 2007 1 Array Elements An array is a construct used to group and organize data.

More information

Course Supervisor: Dr. Humera Tariq Hands on Lab Sessions: Ms. Sanya Yousuf

Course Supervisor: Dr. Humera Tariq Hands on Lab Sessions: Ms. Sanya Yousuf Course Supervisor: Dr. Humera Tariq Hands on Lab Sessions: Ms. Sanya Yousuf UML to represent and using single object Practice writing code for class Practice tostring( ) function Practice writing your

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

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

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

CS 101 Spring 2007 Midterm 2 Name: ID:

CS 101 Spring 2007 Midterm 2 Name:  ID: You only need to write your name and e-mail ID on the first page. This exam is CLOSED text book, closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts, so be sure

More information

Classes Classes 2 / 35

Classes Classes 2 / 35 Classes 1 / 35 Classes Classes 2 / 35 Anatomy of a Class By the end of next lecture, you ll understand everything in this class definition. package edu. gatech. cs1331. card ; import java. util. Arrays

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information