Brain Re-Wiring Time. CS121: Computer Programming I. How to Tackle a Problem? Agenda. Making Changes - which localises change?

Size: px
Start display at page:

Download "Brain Re-Wiring Time. CS121: Computer Programming I. How to Tackle a Problem? Agenda. Making Changes - which localises change?"

Transcription

1 CS121: Computer Programming I Brain Re-Wiring Time Object-Oriented Primer Dr Olly Gotel ogotel@pace.edu Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223 Week 9, Slide 1 CS121/IS223 Week 9, Slide 2 Agenda Many ways to tackle a problem Design example and important design concepts Exercise -- OO design -- thinking with objects Important object-oriented (OO) concepts Role-playing demo to illustrate some of these concepts by simulating OO program execution (maybe in a couple of weeks) Revisiting methods and re-looking at classes CS121/IS223 Week 9, Slide 3 How to Tackle a Problem? Decomposition - handling complexity by the principle of divide & conquer Tends to involve Two forms of decomposition constructing Process-oriented: according to hierarchies steps or functions Object-oriented: according to behaviour of autonomous objects Both valid, but current claims for superiority of OO Stronger framework, reuse of common abstractions & resilient under change CS121/IS223 Week 9, Slide 4 2 Types of Decomposition Making Changes - which localises change? Transaction Transaction Get Transaction Open Passbook Checking Open Open Bonus Open Passbook Withdraw Withdraw Checking Withdraw Bonus Withdraw Open Deposit Withdraw Get Transaction Open Passbook Checking Open Open Bonus Open Passbook Withdraw Withdraw Checking Withdraw Bonus Withdraw Open Deposit Withdraw Account Deposit Account Loadsadosh Open Deposit Loadsadosh Withdraw ihs ihs ihs Passbook Deposit Checking Deposit Bonus Deposit Other object(s) ihs ihs ihs Passbook Deposit Checking Deposit Bonus Deposit Other object(s) ihs Loadsadosh Deposit Passbook Account Checking Account Bonus Account Passbook Account Checking Account Week Bonus Slide Account 5 CS121/IS223 9, CS121/IS223 Loadsadosh Week 9, Slide Account 6 1

2 Design Example - starting object think Design Example No right or wrong here! A conceptual design for a small, one-branch bank A simple design for a small one-branch bank The whole thing, not just the computer part What are the THINGS? What can they do? Think - how would someone on the street RECOGNISE this as a small bank? [Sample solution from Cockburn 1998] CS121/IS223 Week 9, Slide 7 CS121/IS223 Week 9, Slide 8 Design Concepts CRC Cards Items required for good design [Cockburn 1998]: Name of key components, or things, in the system Vault What it is called Purpose, basic function, or main *responsibility* of each thing Holds the money Teller Key communication paths between them List of the services provided What it does What it interacts with CS121/IS223 Week 9, Slide 9 CS121/IS223 Week 9, Slide 10 STEP 1 CRC Cards - use them to think! Exercise Thinking With Objects What it does Class name Responsibilities (i.e. services it provides) What it is called Collaborators (i.e. other classes this class relies on for services) What it uses CS121/IS223 Week 9, Slide 11 You are contractors who just won a bid to design a custom coffee vending machine for the employees of Acme Works to use. Arnold, the owner, wants his own, custom design. He is, however, a cheapskate. Arnold tells us he wants a simple machine. All he wants is a machine that serves coffee for 35 cents, with or without sugar & creamer. He expects you to be able to put this little machine together quickly & for little cost You get together & decide there will be a coin slot & coin return, coin return button, & four other buttons: black, white, black with sugar, & white with sugar Source: [Cockburn 1988] CS121/IS223 Week 9, Slide 12 2

3 Design the Coffee Machine Using Objects Candidate Design 1 What are the components? What are their responsibilities? Which components rely on which other components for services? How do they work together to deliver the simple service: give coffee for 35 cents? Which component knows the price of the drink? Which component knows how to make the drink? Create the CRC cards for these Run some scenarios does it work? Enact the CRC cards Draw this! CS121/IS223 Week 9, Slide 13 [Sample solution from Cockburn 1998] CS121/IS223 Week 9, Slide 14 Interaction Diagram for Design 1 Does Your Design Support Change? STEP 2 After 5 machines are installed & have been operating for a while, Arnold comes along & says, "I would like to add bouillon, at twenty-five cents. Change the design." You add one more button for bouillon & one more container for bouillon powder How else do you change your design? [Cockburn 1998] CS121/IS223 Week 9, Slide 15 CS121/IS223 Week 9, Slide 16 Candidate Design 2 Interaction Diagram for Design 2 [Sample solution from Cockburn 1998] CS121/IS223 Week 9, Slide 17 [Cockburn 1998] CS121/IS223 Week 9, Slide 18 3

4 Analysis of Designs 1 & 2 Yet Another Change! STEP 3 Design to localise change Beware of super components distribute the responsibilities Create some CRC cards to help you check that your design works by running some scenarios of use List as many other changes & additions you believe Arnold may ask you to make in the future Arnold comes back with a brilliant idea. He has heard that some companies use their company badges to directly debit the cost of coffee purchases from their employees' paychecks. Since his employees already have badges, he thinks this should be a simple change. You add a badge reader & link to a payroll system What else? CS121/IS223 Week 9, Slide 19 CS121/IS223 Week 9, Slide 20 Candidate Design 3 Move Over Starbucks! STEP 4 [Sample solution from Cockburn 1998] CS121/IS223 Week 9, Slide 21 People are starting to buy Starbucks lattes instead of Arnold's coffees. So Arnold wants the machine modified just slightly, so that he can create a "drink of the week." He wants to be able to add new drinks and change prices any time, to match his competition. He wants to be able to add espresso, cappuccino, hot chocolate, latte, choco-latte, steamed mil, soy chai in short, anything he can mix together. You add a couple more buttons, a milk steamer & dispenser, & some more powder dispensers. You need a really good, robust design, so that you or Arnold can change the products & prices at will, without tearing the machine apart any further. CS121/IS223 Week 9, Slide 22 Candidate Design 4 Interaction Diagram for Design 4 [Sample solution from Cockburn 1998] CS121/IS223 Week 9, Slide 23 [Cockburn 1998] CS121/IS223 Week 9, Slide 24 4

5 Reference for Design Exercise Read all about it! On my web-site Recommended Good Design Takes Time Simple Object-Oriented Analysis & Design, Parts 1 & 2, Alistair Cockburn, CUJ, May & June 1998: /cuj9805cockburn/ /cuj9806cockburn/ Supports easy change Uses abstractions from the domain Satisfies the need today & tomorrow! Rare to get it perfectly the first time you must be prepared to learn and iterate CS121/IS223 Week 9, Slide 25 CS121/IS223 Week 9, Slide 26 C-class; R-methods; C-method calls Classes, Objects & Methods Hello World in Java (Non-OO) MUST call this file HelloAgain.java public class MessageMaker{ public static void main(string[] args) { Message mymessage = new Message(); mymessage.printmessage(); mymessage.changemessage( goodbye ); mymessage.printmessage(); (Message.java) public class Message{ private String m = hello ; public void printmessage() { System.out.println(m); public void changemessage (String newmessage) { m = newmessage; Other methods here // Another Hello World Program // HelloAgain.java public class HelloAgain { public static void main(string[] args) { System.out.println("Hello World!"); REMEMBER THIS? Must name the file after this CS121/IS223 Week 9, Slide 27 CS121/IS223 Week 9, Slide 28 Hello World in Java (OO) TRY THIS NOW!!! Object-Oriented Concepts // Yet Another Hello World Program // HelloWorld.java public class HelloWorld { public static void main(string[] args) { Hello hello = new Hello(); hello.printhello(); Must call this file HelloWorld.java // A Hello class for Yet Another Hello World Program // Hello.java public class Hello { public void printhello() { System.out.println("Hello World!"); MUST call this file Hello.java CS121/IS223 Week 9, Slide 29 Classes Objects Methods Messages & message passing Parameters & arguments Return types & voids Encapsulation & information hiding Instance variables & class variables State Access modifiers Overriding & overloading* Interfaces* Inheritance* Polymorphism* * later We we will look at these in detail and look more at the other concepts in the follow -up course CS121/IS223 Week 9, Slide 30 5

6 Next Few Weeks: what they mean & how to use! Role-playing Demo At some point object state message attribute identity behaviour relationship class abstraction polymorphism interface generalisation & specialisation inheritance encapsulation message passing method dynamic binding instance CS121/IS223 Week 9, Slide 31 How an OO program works - to illustrate concepts in everyday terms CS121/IS223 Week 9, Slide 32 object has state + identity + behaviour In Plain Terms, an Object is Example Objects object Something that represents an atomic entity Something you can uniquely identify (identity) Something that encapsulates data as its state Something you can send messages to, causing it to respond/behave in some way Something whose behaviour depends on its internal state (which may change) Has a public interface & private internals CS121/IS223 Week 9, Slide 33 Passive objects One loaf of bread One packet of herbal tea Invoice sent to A Farm, Malvern Active objects Lorry "M235 BCM ; Van "N683 CNM" Fax machine in Richard Green's office Human agents Richard Green; David Brown (Executive) Structure objects Marketing Department CS121/IS223 Week 9, Slide 34 object has state + identity + behaviour Looking Inside an Object Gordon, Junior Librarian, as object State All the data the object currently encapsulates state M T W T F Attributes Name: Gordon Position: Junior Librarian Age: 25 Salary: 12, Relations Operations Loan out books Rename position Amend salary Data is defined in terms of valued attributes (characteristic features - name / value pairs) The value of some attributes is fixed (immutable) attribute The value of some attributes can change (mutable) Supervisor Timetable Equipment Values of the attributes are the state of the object student_id; registered_courses; weight; date_of_birth CS121/IS223 Week 9, Slide 35 CS121/IS223 Week 9, Slide 36 6

7 Identity identity Behaviour behaviour Attribute values may change, so don t clearly pin -point the object over time Identity makes it possible to distinguish any object in an unambiguous way & independent from its state Characterises the object to give persistence Like a natural key or unique handle phone number student_id CS121/IS223 Week 9, Slide 37 Operations enable an object to act & react Objects can receive certain messages & act upon them The set of messages the object can understand is generally fixed & defined in its interface Reaction to messages may depend on current attribute values (i.e. state); it may even change the state on flickswitch CS121/IS223 Week 9, Slide 38 off message message passing Message Message Passing Messages are sent to objects to trigger behaviour Structure - keyword selector & optional arguments Arguments are values being passed to the object Identity: myclock Attribute: currenttime Message: resettime(newtime) Message: telltime Object may respond to a message by sending a message to another object! Objects therefore interact by passing messages to one another (i.e. object interaction) A message requests an object to perform an operation or service A message consists of a name & any arguments CS121/IS223 Week 9, Slide 39 CS121/IS223 Week 9, Slide 40 Interface interface Method method An object can have public & private interface An object s public interface defines the messages it will accept & that all can use An object s private interface can only be used by the object itself or those who are privileged Structure - selector, required arguments & what will be returned public -> resettime(newtime: Time) public -> telltime() : Time private -> time : Time CS121/IS223 Week 9, Slide 41 A description that determines how an object reacts to a message (e.g. a piece of code to implement the operation) Methods are called in response to messages sent to objects The operation performed is determined by the the object s class & the value of the object s attributes - so the method has full access to the object s state Matching a message name to a method is called binding CS121/IS223 Week 9, Slide 42 7

8 Dynamic binding dynamic binding Encapsulation encapsulation The same message can be sent to different objects Each object can bind the message to a different method, as defined by its class Dynamic (late) binding refers to the process of identifying what code should be executed as the result of receiving a message Reduces coupling between objects Enables pluggability & substitutability Behaviour & information are encapsulated in objects (we say objects are strongly encapsulated) From outside, an object can only be manipulated via its public interface; the internal state is private & can only be changed by the object itself Other objects can only know operations on the object, not how they work Necessary prerequisite for information hiding & programming by contract CS121/IS223 Week 9, Slide 43 CS121/IS223 Week 9, Slide 44 Class class Class (in UML) class Objects can have a lot in common & can lead to much duplication A class defines the structure & behaviour of a particular kind of object - acting as a template or blueprint Classes represent groups of objects with the same behaviour & information structures Every object belongs to a class (i.e. is an instance of a single class), though a class may have many instance objects Classes represent abstractions ann?timepiece? student CS121/IS223 Week 9, Slide 45 jo We call this representation of a book an abstraction Name compartment Instance variables Method definitions Book title: String copiesonshelf(): int borrow(c:copy) Parameters & their types Class name Name Type Return type CS121/IS223 Week 9, Slide 46 Instance & Instantiation instance Classes & Objects Instantiation - the process of creating a new object belonging to a class Truck Instance - the resulting object Note that this object is a new thing with its own identity Attributes Registration No. Weight Fuel Relations The state of the new object must be initialised (i.e. its instance variables given values) Driver Trailer Operations Create (Truck) Deliveries Goods Refuel Delete (Truck) Values will instance level Classes define structure & behaviour of a system Objects represent the *actual* system relationships classes links objects CS121/IS223 Week 9, Slide 47 CS121/IS223 Week 9, Slide 48 8

9 Key Points You can approach a problem in different ways: Procedurally, by breaking a problem down into smaller problems that compose to solve the overall problem (you create a tree) Using communicating objects (you create a network) OO design is natural & scaleable, but requires thinking with objects, being prepared to iterate & giving up the notion of global control Coming Up Next Banks, coffee machines & trek species are all objects before we look at how to define them (using classes) & create instances (objects), we will look at communication between objects & the services they provide (methods) Java how it deals with classes, objects & methods starting with methods again programming the OO way (you need to have done your prep work!) What is really going on? Program control flow OO programming concepts support this way of thinking & solving problems CS121/IS223 Week 9, Slide 49 CS121/IS223 Week 9, Slide 50 Agenda How to define & use simple classes (with instance variables & methods) may be new How to create instances of classes (objects) & what are these things anyway? may be new How to define & use methods (should be a recap so go through these slides at home for homework): main method & constructors Parameters/arguments & returns Visibility (access modifiers) Method overloading Java Ingredients So Far Variables, assignment, operators Expressions, statements, compound statements Control structures selection, iteration Lots of other useful bits & pieces along the way arrays, files, etc Aim now to write OO programs Need - to create your own objects, which means writing your own class types One step at a time CS121/IS223 Week 9, Slide 51 CS121/IS223 Week 9, Slide 52 How to Write an OO Program in Java (Simplified) Identify classes needed Identify methods & variables needed by objects of those classes Write classes Run program by creating objects in a main method (often in a driver class) & calling the object s methods Objects then call each other s methods CS121/IS223 Week 9, Slide 53 Reminder Class: template for creating objects of a particular type, defining data about the objects (instance variables) & operations they can carry out (methods) Object: instance of a class, given a name & actual data values it can carry out the operations Methods are the building block of OOP they should be small, cohesive & general-purpose KEY WORD Encapsulation: combination of data & operations in a single self-contained object CS121/IS223 Week 9, Slide 54 9

10 Classes & Methods & Objects Written a Method, How Do You Use It? public class ExampleClass{ public void methodone(){ Statements public void methodtwo(){ Statements Instance object created ExampleClass myobj = new ExampleClass(); myobj.methodone(); myobj.methodtwo(); A class can declare a number of methods Constructor Methods are called on instance objects of the class CS121/IS223 Week 9, Slide 55 Methods are called on objects but when you start a program running, you have no objects Remember the main method: public static void main(string[] args) { Means method does NOT need to be called on an object main creates object(s) & calls their methods the objects then take over the show main is special write no other static methods on this course CS121/IS223 Week 9, Slide 56 Classes Class name: Car Data: Colour Licence Speed Fuel Methods: Accelerate Brake Colour: orange Licence: J342 Speed: 20 mph Fuel: 2 gallons Colour: red Licence: RACER Speed: 100 mph Fuel: 15 gallons A class is a data type The Same Information in UML Unified Modelling Language a class diagram Car - colour: string - licence: string - speed: double - fuel: double + accelerate(double mss, double t): void + brake(double mss, double t): void + honk(): void Class name Data Methods CS121/IS223 Week 9, Slide 57 CS121/IS223 Week 9, Slide 58 Classes & Objects One class, many objects Writing the Java Class Definition - colour: string - licence: string - speed: double - fuel: double Car + accelerate(double mss, double t): void + brake(double mss, double t): void + honk(): void Each Java class definition should be stored in its own file (filename the same as class name, with.java extension just as you have been doing) e.g. Car.java Your program can have many classes (so many files), but only one has a main method amongst them It is a good idea to put this in a driver or test class Put all your classes in the same directory for now CS121/IS223 Week 9, Slide 59 CS121/IS223 Week 9, Slide 60 10

11 Write the Classes Primary class Car Race public class Car{ private String colour, licence; private double speed, fuel; public void honk(){ System.out.println( Beep Beep! ); Test class with main() method Instance variables private means can only be changed inside the class (by its methods) Method public means that it can be called from outside the class by objects of Car class public class CarTester{ public static void main(string[] args){ Car mycar = new Car(); Make a new car mycar.honk(); object & call it mycar Get mycar to honk its horn CS121/IS223 Week 9, Slide 61 CS121/IS223 Week 9, Slide 62 Objects & Classes Object: distinguishing characteristics data associated with it (attributes or instance variables) can perform certain actions (methods) Class: defines a type of object the blueprint/template/definition Methods Can structure programs as a collection of methods that call one another Methods help to organise code - they should be small, cohesive & general-purpose Methods can have parameters & so take arguments this makes them more general-purpose Methods can return values (or void) Your program always has ONE main method & this is where execution starts Examples of objects & classes? CS121/IS223 Week 9, Slide 63 CS121/IS223 Week 9, Slide 64 From Procedural to OO Programming (OOP) Before: all code was in a class that you gave the same name as your file all the class code was inside a main method this code was executed in sequential manner A program was a sequence of statements Now: still can have a single class / file for hybrid code in the main method creates an object of the class type, then calls its methods (i.e. tells it to do things) the doing code is packaged into named methods no longer any sequence as such more interesting A program is a collection of method-calling objects Onward to OO You can approach a problem in different ways: Procedurally, by breaking a problem down into smaller problems that compose to solve the overall problem (you create a tree) Using communicating objects (you create a network) OO design is natural & scaleable, but requires thinking with objects & being prepared to iterate to improve your thinking OO programming concepts support this way of thinking & solving problems CS121/IS223 Week 9, Slide 65 CS121/IS223 Week 9, Slide 66 11

12 Benefit of Programming this Way? Key Points Class: template for creating objects of a particular type, defining data about the objects (instance variables) & operations they can carry out (methods) Object: instance of a class, given a name & actual data values it can carry out the operations Methods are the building block of OOP they should be small, cohesive & general-purpose KEY WORD Encapsulation: combination of data & operations in a single self-contained object CS121/IS223 Week 9, Slide 67 CS121/IS223 Week 9, Slide 68 EXTRA SLIDES TO HOME A Quick Reminder on Methods Go through this material again (presented earlier in the course) and see if you can try a few things out in code, coupled with support from your text book Writing Java Programs Only written very small programs to date using one class (the name of your program) OO, but not really OO How do your programs work? How do you write really BIG programs? How do you write OO ones? One big class, with lots of statements, loops & selections inside? repeats bits of code jumps all over the place It would just be a mess needs structure CS121/IS223 Week 9, Slide 69 CS121/IS223 Week 9, Slide 70 Helping With Digestion Organising Code Managing complexity Which is easier to talk about or refer to: a sandwich, a packet of chips, a cookie, some fruit, a carton of juice? a box lunch? Package stuff up and give it a label to refer to! We group programming statements to make the task of programming more comprehensible Statements are generally grouped when, together, they perform some task A name is assigned to such blocks of code (functions, procedures, subroutines, modules, methods) so this name can be referred to in place of all the statements CS121/IS223 Week 9, Slide 71 Every programming language has its own way for doing these things CS121/IS223 Week 9, Slide 72 12

13 Chunky Variable a chunk of data with a name Method a chunk of code with a name The foundations of reuse CS121/IS223 Week 9, Slide 73 Packaging Code printsquare: Refer to printsquare() whenever we want to use the sequence of statements (this is abstraction) Write once, debug once, use many times, update in one place In Java, we call this a method & declare it inside a class CS121/IS223 Week 9, Slide 74 Methods in Java A method is a named sequence of programming statements Clarification Some programming languages have functions or procedures Python has functions for e.g. To use a method, you call it but you have to state where the method can be found (i.e. which class the code is inside) You do this by calling the method on an object of the class: General - objectname.methodname(); Specific - myobject.printsquare(); Static methods are called on a class no objects needed CS121/IS223 Week 9, Slide 75 Java has object methods a bit like a function that an object can perform terry.forwardmarch(); object of class turtle method Variable of a class type names an object (e.g. terry) CS121/IS223 Week 9, Slide 76 Code Structure Classes & Methods Source file (ClassName.java) Method 1 Statement Statement Method 2 Statement Class CS121/IS223 Week 9, Slide 77 public class ExampleClass{ public void methodone(){ Statements public void methodtwo(){ Statements Instance object created - one particular ExampleClass ExampleClass myobject = new ExampleClass(); myobj.methodone(); myobj.methodtwo(); A class can declare a number of methods (responsibilities, services, behaviours) Constructor - a method with same name as class to make an instance object of this class Methods are called on instance objects of the class (dot notation) CS121/IS223 Week 9, Slide 78 13

14 Classes & Methods - Example public class SquareClass{ Method name public void printsquare(){ for (int i = 0; i < 5; i++) System.out.println( ); Method code in braces Methods are just a nice way of packaging your code now just call the method rather than repeat the code Class name CS121/IS223 Week 9, Slide 79 What Do These Mean? public class SquareClass{ public void printsquare(){ for (int i = 0; i < 5; i++) System.out.println( ); public can call the method from anywhere in a program (if object is accessible) a visibility/access modifier void method returns no value back to the place of the method call, just does something handy CS121/IS223 Week 9, Slide 80 Written a Method, How Do You Use It? Hybrid OO - meaning I am making an instance of a class in the class itself better to have a separate DRIVER class that does this but easier for small things for now Using Our Example Methods are called on objects but when you start a program running, you have no objects Remember the main method: public static void main(string[] args){ Means method does NOT need to be called on an object main creates object(s) & calls their methods the objects then take over the show Only one main method in a program, even if lots of java files CS121/IS223 Week 9, Slide 81 public class SquareClass{ public void printsquare(){ for (int i = 0; i < 5; i++) System.out.println( ); public static void main(string[] args){ SquareClass myobj = new SquareClas s(); myobj.printsquare(); Constructor CS121/IS223 Week 9, Slide 82 Classes, Objects & Methods Not the best way Future > class types & driver classes Program Flow Like being interrupted by a phone call but you carry on doing what you were previously doing when it is over Instance variable - gpa - each student object has own value for gpa (Student.java) public class Student { private int gpa=0; public int getgpa() { return this.gpa; public void setgpa(int newgpa) { this.gpa=newgpa; public static void main(string[] args) { Student s1 = new Student(); System.out.println(s1.getGpa()): Other methods here CS121/IS223 Week 9, Slide 83 A method call changes the flow of a program The program jumps & control passes to the method (it may be in an external class/file) Control returns to the point it left when the method has finished With conditionals (branches), loops (repeats) & methods (side-tracks) we can get quite interesting program flow CS121/IS223 Week 9, Slide 84 14

15 Built-in Methods Black-box programming How Many Built-in Methods? Methods provided by the programming language to carry out routine or complex things: System.out.println( bla ); We know nothing about how built-in methods like println are coded We don t need to know anything, other than: how to use the method (i.e. how to call it & whether to pass it any arguments - we are passing println a string here) the type of value the method returns println returns nothing - it is void) A sort of protocol CS121/IS223 Week 9, Slide 85 There are an enormous number of built-in methods to take advantage of (see the API)! However, you are not expected to know about or use all of these you will find things as & when you need them They can save you some work! CS121/IS223 Week 9, Slide 86 User-Defined Methods When there is no built-in method to do what you want to do, you have to roll your own It is exactly like a built-in method, but YOU write the code Your method may do one specific thing, but it is often smarter to make it general purpose Example We want to write a program to print out this sign ******************************************************* ******************************************************* Welcome ******************************************************* ******************************************************* ******************************************************* ******************************************************* Example from Dr Courtney CS121/IS223 Week 9, Slide 87 CS121/IS223 Week 9, Slide 88 A Class & Its Methods - Declaring Driver Class Making an Object; Calling its Methods public class SignClass{ public void printtwolines(){ System.out.println(" *******************************"); System.out.println(" *******************************"); public void printwelcome(){ System.out.println(" Welcome"); public void printfourlines(){ for(int i=1; i <=4; i++) System.out.println("********************************"); i is local / temporary variable with restricted scope Why use methods? CS121/IS223 Week 9, Slide 89 public class SignDemo{ public static void main(string[] args){ SignClass welcomesign = new SignClass(); //instantiating an object welcomesign.printtwolines(); //invocation of method in object s class definition welcomesign.printwelcome(); //invocation of method welcomesign.printfourlines(); //invocation of method Why do this? CS121/IS223 Week 9, Slide 90 15

16 Try it! Making Methods More General (i) Go back 2 slides make a SignClass class exactly as shown Go back 1 slide make a SignDemo class exactly as shown 2 java files in the same source folder - compile and run see what happens Then, look at the code changes to these 2 classes in the following slides, make the changes and keep re -running your code CS121/IS223 Week 9, Slide 91 public void printlines(int number){ Parameter for(int i=1; i <=number; i++) System.out.println("*********************"); Create the above method in the SignClass public class SignDemo{ public static void main (String[] args){ SignClass welcomesign = new SignClass(); welcomesign.printlines(2); welcomesign.printwelcome(); welcomesign.printlines(4); Values for parameters to pass into methods should agree in type, quantity, and position CS121/IS223 Week 9, Slide 92 Aside This is called the method SIGNATURE or method declaration public void printlines(int number) The return type Visibility/access modifier Method name Parameter - variable name and its type Making Methods More General (ii) public class SignDemo{ public static void main(string[] args){ SignClass forsalesign = new SignClass(); forsalesign.printlines(2); forsalesign.decideonmessage(); forsalesign.printmessage(); forsalesign.printlines(4); Need to declare some instance data for the SignClass, so each actual sign object we make can store its own unique message CS121/IS223 Week 9, Slide 93 CS121/IS223 Week 9, Slide 94 Making Methods More General (iii) public class SignClass{ private String message= ; Making a General Purpose Method Try the next example too public void printlines(int number){ for (int i=1; i<=number; i++) System.out.println(" ******************"); public void printmessage(){ System.out.println(" " + message"); public void decideonmessage(){ System.out.println( What message do you want?"); message = scan.nextline(); Make your Scanner object the usual way CS121/IS223 Week 9, Slide 95 CS121/IS223 Week 9, Slide 96 16

17 Returning to our Example Hybrid OO Squares of Any Size? Varied behaviour a better abstraction public class SquareClass{ Revisiting a few concepts here Parameter to method public void printsquare(){ for (int i = 0; i < 5; i++) System.out.println( ); public static void main(string[] args){ SquareClass myobj = new SquareClas s(); myobj.printsquare(); Constructor Change the method to print a square of ANY size CS121/IS223 Week 9, Slide 97 Parameter variable public void printsquare(int side){ for (int row = 0; row < side; row++){ for (int col = 0; col < side; col++){ Scope of side? System.out.print( + ); System.out.println( \n ); To call: myobj.printsquare(8); Change the method to print a rectangle of ANY size New line character Argument to method initialises side (the parameter variable) CS121/IS223 Week 9, Slide 98 Rectangles of Any Size? public void printrect(int rows, int cols){ for (int row = 0; row < rows; row++){ for (int col = 0; col < cols; col++){ System.out.print( + ); System.out.println( \n ); An even better abstraction To call: myobj.printrect(2, 4); 2 parameters to method 2 arguments to method types MUST match, so order is important Rectangles Using Any Character? Better abstraction yet! 3 parameters to method public void printrect(int rows, int cols, char ch){ for (int row = 0; row < rows; row++){ for (int col = 0; col < cols; col++){ System.out.print(ch); System.out.println( \n ); 3 arguments to method types MUST match, so order is important Change the method to print a rectangle of ANY size using any character! CS121/IS223 Week 9, Slide 99 To call: myobj.printrect(2, 4, * ); CS121/IS223 Week 9, Slide 100 Methods That Return Values void methods return no value The return Statement in Java Does a calculation & returns a value you must do something with this return value! Parameter is number to square, Type of the return value declared with its type declared public int square(int number){ number = number * number; return number; return statement returns a value & ends the method MUST be present if method declaration/signature returns a type To call & use: int x = myobj.square(3); CS121/IS223 Week 9, Slide 101 Returns a value & ends a method jumps back to where the method was called & inserts its value Methods only return 1 value, but this could be a collection! public int square(int number){ return number * number; statement; NEVER executed Note, constructors have no return type, not even void! CS121/IS223 Week 9, Slide

18 What s the Difference? Parameters / Arguments Scope, access, lifetime Arguments & parameters: two sides of the same coin -- it is just terminology (often used interchangeably) You specify a method signature using parameters You call a method using arguments (i.e. you give actual values for the parameters) When a method is called, arguments are passed into (substituted for) the parameters Be careful of scope - where do these variables exist? CS121/IS223 Week 9, Slide 103 Special kind of variable used to pass data to a method 2 ways Pass by reference: parameter variable in the method refers to the same location in memory as the original variable in the method call change the parameter variable, you change the original variable Placeholder! Pass by value: method makes a temporary copy of the data in the original variable if you change the parameter variable it has NO effect on the original variable CS121/IS223 Week 9, Slide 104 More Terminology Recap Good to make methods as general -purpose & reusable as possible Encapsulation taking some code statements, turning them into a method, then using them as a whole: simpler to refer to & remember as a whole can be used many times, in many places (reuse) other people can use your code & you can use other people s (a clear contract of use) Generalisation writing methods that can do more than one particular thing: a method that can find the factorial of any number is more useful than a method that only finds 5! Methods in Java: parameters specify the type & number of variables used by a method (can have any number) sometimes called formal parameters arguments are the actual values of these variables & they are passed to the method when it is called sometimes called actual parameters scope determines the lifetime of a variable (often delimited by the braces of compound statements & sometimes nested) local / temporary variables are variables declared in a method, & have restricted scope created when scope entered, destroyed when scope exited (names can be reused if scopes disjoint) if your method specifies a non-void return type, it needs a return statement CS121/IS223 Week 9, Slide 105 CS121/IS223 Week 9, Slide 106 Writing Java Programs Using Methods Methods in Java No longer a long sequential list of statements Instead, loosely coupled methods that call each other Create small cohesive methods that do a single thing: if it does many things, split into multiple methods if it is long, split into multiple methods Parameterise your methods to make them general -purpose CS121/IS223 Week 9, Slide 107 A method is a named sequence of programming statements To use a method, you call it but you have to state where the method can be found (i.e. which class the code is inside) You do this by calling the method on an object of the class: General - objectname.methodname(); Specific - obj.printsquare(); Methods are called for an object CS121/IS223 Week 9, Slide

19 Writing Java Programs Using Methods Example Method design try this at home No longer a long sequential list of statements Instead, loosely coupled methods that call each other Create small cohesive methods that do a single thing: if it does many things, split into multiple methods if it is long, split into multiple methods Parameterise your methods to make them general -purpose What is too long or too much? CS121/IS223 Week 9, Slide 109 Assume we will use a single class what would be a good way of splitting up the work involved in getting a sequence of 100 integers from a user & printing them out in ascending order (i.e. what methods would you write)? 3 methods maybe? Do the input thing Do the sorting thing Do the output thing Logical problem decomposition CS121/IS223 Week 9, Slide 110 Example Continued public class Sorter{ Declare the 3 methods in the same class here FOR NOW public static void main(string[] args){ Sorter myobj = new Sorter(); myobj.inputint(); myobj.sortint(); myobj.outputint(); Constructor (a special method) Lazy OO Writing the Methods (i) inputint(): Need to input 100 integers, so need a loop Need a suitable data structure to store them in (use an array) Method will need to return an integer array CS121/IS223 Week 9, Slide 111 CS121/IS223 Week 9, Slide 112 Code public int[] inputint(){ int[] myints = new int[100]; // loop to read in integers return myints; Writing the Methods (ii) sortint(): Need to take an integer array as an argument Need to sort the array (later) Method will need to return a sorted integer array A better method would be flexible & allow the user to say how many integers they want to input CS121/IS223 Week 9, Slide 113 CS121/IS223 Week 9, Slide

20 Code public int[] sortint(int[] myints){ // sort integers return myints; Writing the Methods (iii) outputint(): Need to take an integer array as an argument Need to print out the array elements, so will need a loop Method needs to return nothing, so is void CS121/IS223 Week 9, Slide 115 CS121/IS223 Week 9, Slide 116 Code public void outputint(int[] myints){ // loop to print out integers Changing the main Method public class Sorter{ public static void main(string[] args){ Sorter myobj = new Sorter(); int[] myints = myobj.inputint(); myints = myobj.sortint(myints); myobj.outputint(myints); Many ways to do this CS121/IS223 Week 9, Slide 117 CS121/IS223 Week 9, Slide 118 Also called data members Instance Variables (aka Attributes or Fields) Code Structure - Recap An instance variable belongs to an object & has class scope (i.e. can be used by any instance methods) public class Sorter{ private int[] myints = new int[100]; Declare instance variables public static void main(string[] args){ Sorter myobj = new Sorter(); int[] myints = myobj.inputint(); myints This = now myobj.sortint(myints); simplifies! Declare myobj.outputint(myints); methods Constants: final int MAX = 100; CS121/IS223 Week 9, Slide 119 Source file (ClassName.java) int x; Method 1 Statement Statement Method 2 Statement Class Data declarations - Make these private Method declarations - Make these operate on the declared data CS121/IS223 Week 9, Slide

21 Much Simpler Interfaces Control ordering when methods can be called from outside a class public int[] inputint(){ int[] myints = new int[100]; // loop to read in integers return myints; public void inputint(){ // myints = what is read in public void sortint(){ // sort integers public void outputint(){ // loop to print out integers No need to return it can be void Don t need myints is a variable in class scope, so can access it here SAFE? CS121/IS223 Week 9, Slide 121 The set of methods an object makes available to others to use private void inputint() { private void sortint() { private void outputint() { public void dosorting(){ inputint(); sortint(); outputint(); public static void main(string[] args){ Sorter myobj = new Sorter(); myobj.dosorting(); CS121/IS223 Week 9, Slide 122 How Would Other Objects Use This? Public & Private Called visibility modifiers or access modifiers Contracts to ensure used correctly & in right order Specify order of method call but can t enforce it, so better to wrap things up a bit make all these public methods private & provide a single public method to control what an object is able to do Private variables means can be used by methods in the same class Private methods means can be used by other methods in the same class CS121/IS223 Week 9, Slide 123 Use methods to write small cohesive units of code, but try to make a minimum number of methods public (i.e. public interface should be thin) Public methods should act as access methods providing control over the use of private methods & data Variables can also be declared public or private inside a class it is good practice to make these private & use methods to set & change their values (i.e. getters & setters also known as accessors & mutators) Protected #? Default is public so be careful! CS121/IS223 Week 9, Slide 124 Constructors public class Olly { private int age = 0; public Olly(int newage){ age = newage; public int getage() { return age; Constructors have no return public Olly(){ age = 0; Default constructor Method Overloading To perform the same method on different types of data Same method name with multiple parameter lists (method signature) In Java 5.0, return types can be overloaded too public static void main(string[] args) { Olly babyolly = new Olly(); Olly youngolly = new Olly(21); Overloaded constructor System.out.println(youngOlly.getAge()): CS121/IS223 Week 9, Slide 125 E.g. print(counter); print( Hello! ); Constructors are often overloaded CS121/IS223 Week 9, Slide

22 Key Points Programming gets horribly complex if you don t organise your code Methods provide a way to structure your programs There are built-in methods More interestingly, you can create your own methods we call these user-defined CS121/IS223 Week 9, Slide 127 Things to Try Go through the lecture slides again & ask me questions if you have them Try working with the code fragments in these slides and see how you get on Read your book chapters on methods Finish exercise sheet 2 Work on Lab 1 individually or in pairs Work on LAB1 get as far as you can seek help if you need it CS121/IS223 Week 9, Slide 128 What You Should ALWAYS Do! Coming up Next If you want to learn to program in an OO way (with Java), you need to read the course text not just once, but again & again the weekly sessions can only help steer a course for you through this material You should try all the exercises & as many as the programming projects as humanely possible -- it requires your commitment to practice! To accompany this week s class, & if you want to keep up, it would be a good idea to ensure you can master the following exercises: - If you have 3rd edition of text: exercises & programming projects 4.1, 4.2, 4.3 & If you have 4-6th edition of text: exercises , 6.2, 6.3, 6.4 & programming projects 4.1, 4.3 & 6.1 I will always look at your work & help you with problems if you come to me during office hours CS121/IS223 Week 9, Slide 129 Lots of practice with designing your own classes Objects & object reference variables - what are these object things anyway? Let s look underneath Understanding parameter passing there is more going on behind the scenes than you may think! CS121/IS223 Week 9, Slide

CS121: Computer Programming I

CS121: Computer Programming I CS121: Computer Programming I Object-Oriented Primer Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming

More information

CS121: Computer Programming I

CS121: Computer Programming I CS121: Computer Programming I A) Practice with Java Control Structures B) Methods Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours

More information

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements CS121: Computer Programming I A) Practice with Java Control Structures B) Methods Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours

More information

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

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes CS111: PROGRAMMING LANGUAGE II Lecture 1: Introduction to classes Lecture Contents 2 What is a class? Encapsulation Class basics: Data Methods Objects Defining and using a class In Java 3 Java is an object-oriented

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

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

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology Computer Science II OO Programming Classes Scott C Johnson Rochester Institute of Technology Outline Object-Oriented (OO) Programming Review Initial Implementation Constructors Other Standard Behaviors

More information

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

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

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

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want

More information

Object Oriented Software Development CIS Today: Object Oriented Analysis

Object Oriented Software Development CIS Today: Object Oriented Analysis Object Oriented Software Development CIS 50-3 Marc Conrad D104 (Park Square Building) Marc.Conrad@luton.ac.uk Today: Object Oriented Analysis The most single important ability in object oriented analysis

More information

CSCI 161 Introduction to Computer Science

CSCI 161 Introduction to Computer Science CSCI 161 Introduction to Computer Science Department of Mathematics and Computer Science Lecture 2b A First Look at Class Design Last Time... We saw: How fields (instance variables) are declared How methods

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x ); Chapter 5 Methods Sections Pages Review Questions Programming Exercises 5.1 5.11 142 166 1 18 2 22 (evens), 30 Method Example 1. This is of a main() method using a another method, f. public class FirstMethod

More information

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

CT 229 Arrays in Java

CT 229 Arrays in Java CT 229 Arrays in Java 27/10/2006 CT229 Next Weeks Lecture Cancelled Lectures on Friday 3 rd of Nov Cancelled Lab and Tutorials go ahead as normal Lectures will resume on Friday the 10 th of Nov 27/10/2006

More information

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

Principles of Object Oriented Programming. Lecture 4

Principles of Object Oriented Programming. Lecture 4 Principles of Object Oriented Programming Lecture 4 Object-Oriented Programming There are several concepts underlying OOP: Abstract Types (Classes) Encapsulation (or Information Hiding) Polymorphism Inheritance

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

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

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited Table of Contents Date(s) Title/Topic Page #s 11/6 Chapter 3 Reflection/Corrections 56 Chapter 4: Writing Classes 4.1 Objects Revisited 57 58-59 look over your Ch 3 Tests and write down comments/ reflections/corrections

More information

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

More information

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay Computer Science and Engineering Indian Institue of Technology Bombay November 27, 2004 What is Object Oriented Programming? Identifying objects and assigning responsibilities to these objects. Objects

More information

Day 2. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 2. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 2 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda a quick look back (Monday s class) assignments a1 is due on Monday a2 will be available on Monday and is due the following

More information

Midterms Save the Dates!

Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Creating Your Own Class Lecture 7 Readings This Week s Reading: Ch 3.1-3.8 (Major conceptual jump) Next Week: Review Ch 1-4 (that

More information

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 5 Modified by James O Reilly Class and Method Definitions OOP- Object Oriented Programming Big Ideas: Group data and related functions (methods) into Objects (Encapsulation)

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

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

CPS122 Lecture: Defining a Class

CPS122 Lecture: Defining a Class Objectives: CPS122 Lecture: Defining a Class last revised January 14, 2016 1. To introduce structure of a Java class 2. To introduce the different kinds of Java variables (instance, class, parameter, local)

More information

LECTURE 3: SOFTWARE DESIGN. Software Engineering Mike Wooldridge

LECTURE 3: SOFTWARE DESIGN. Software Engineering Mike Wooldridge LECTURE 3: SOFTWARE DESIGN Mike Wooldridge 1 Design Computer systems are not monolithic: they are usually composed of multiple, interacting modules. Modularity has long been seen as a key to cheap, high

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

02291: System Integration

02291: System Integration 02291: System Integration Hubert Baumeister hub@imm.dtu.dk Spring 2011 Contents 1 Recap 1 2 More UML Diagrams 2 2.1 Object Diagrams........................................... 2 2.2 Communication Diagrams......................................

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

Building custom components IAT351

Building custom components IAT351 Building custom components IAT351 Week 1 Lecture 1 9.05.2012 Lyn Bartram lyn@sfu.ca Today Review assignment issues New submission method Object oriented design How to extend Java and how to scope Final

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

1. Write two major differences between Object-oriented programming and procedural programming?

1. Write two major differences between Object-oriented programming and procedural programming? 1. Write two major differences between Object-oriented programming and procedural programming? A procedural program is written as a list of instructions, telling the computer, step-by-step, what to do:

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

CS113: Lecture 4. Topics: Functions. Function Activation Records

CS113: Lecture 4. Topics: Functions. Function Activation Records CS113: Lecture 4 Topics: Functions Function Activation Records 1 Why functions? Functions add no expressive power to the C language in a formal sense. Why have them? Breaking tasks into smaller ones make

More information

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 1 Problem Ralph owns the Trinidad Fruit Stand that sells its fruit on the street, and he wants to use a computer

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 4 Chapter 4 1 Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have.

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

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

CS 1302 Chapter 9 (Review) Object & Classes

CS 1302 Chapter 9 (Review) Object & Classes CS 1302 Chapter 9 (Review) Object & Classes Reference Sections 9.2-9.5, 9.7-9.14 9.2 Defining Classes for Objects 1. A class is a blueprint (or template) for creating objects. A class defines the state

More information

CPS122 Lecture: Course Intro; Introduction to Object-Orientation

CPS122 Lecture: Course Intro; Introduction to Object-Orientation Objectives: CPS122 Lecture: Course Intro; Introduction to Object-Orientation 1. To introduce the course requirements and procedures. 2. To introduce fundamental concepts of OO: object, class Materials:

More information

CSC207 Week 3. Larry Zhang

CSC207 Week 3. Larry Zhang CSC207 Week 3 Larry Zhang 1 Announcements Readings will be posted before the lecture Lab 1 marks available in your repo 1 point for creating the correct project. 1 point for creating the correct classes.

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

CSE 70 Final Exam Fall 2009

CSE 70 Final Exam Fall 2009 Signature cs70f Name Student ID CSE 70 Final Exam Fall 2009 Page 1 (10 points) Page 2 (16 points) Page 3 (22 points) Page 4 (13 points) Page 5 (15 points) Page 6 (20 points) Page 7 (9 points) Page 8 (15

More information

Object- Oriented Design with UML and Java Part I: Fundamentals

Object- Oriented Design with UML and Java Part I: Fundamentals Object- Oriented Design with UML and Java Part I: Fundamentals University of Colorado 1999-2002 CSCI-4448 - Object-Oriented Programming and Design These notes as free PDF files: http://www.softwarefederation.com/cs4448.html

More information

Methods. Methods. Mysteries Revealed

Methods. Methods. Mysteries Revealed Methods Methods and Data (Savitch, Chapter 5) TOPICS Invoking Methods Return Values Local Variables Method Parameters Public versus Private A method (a.k.a. func2on, procedure, rou2ne) is a piece of code

More information

Introduction to Computers and Programming Languages. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Introduction to Computers and Programming Languages. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Introduction to Computers and Programming Languages CS 180 Sunil Prabhakar Department of Computer Science Purdue University 1 Objectives This week we will study: The notion of hardware and software Programming

More information

Introduction to Software Development (ISD) Week 3

Introduction to Software Development (ISD) Week 3 Introduction to Software Development (ISD) Week 3 Autumn term 2012 Aims of Week 3 To learn about while, for, and do loops To understand and use nested loops To implement programs that read and process

More information

Software Development 2

Software Development 2 Software Development 2 Course Map This module introduces some of the techniques programmers use to create applications and programs. Introduction Computer Principles and Components Software Development

More information

Exam Duration: 2hrs and 30min Software Design

Exam Duration: 2hrs and 30min Software Design Exam Duration: 2hrs and 30min. 433-254 Software Design Section A Multiple Choice (This sample paper has less questions than the exam paper The exam paper will have 25 Multiple Choice questions.) 1. Which

More information

Midterms Save the Dates!

Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Instance Variables if Statements Readings This Week s Reading: Review Ch 1-4 (that were previously assigned) (Reminder: Readings

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

Object-Oriented Design. Module UFC016QM. and Programming. Objects and Classes. O-O Design Unit 2: Faculty of Computing, Engineering

Object-Oriented Design. Module UFC016QM. and Programming. Objects and Classes. O-O Design Unit 2: Faculty of Computing, Engineering Module UFC016QM Object-Oriented Design and Programming O-O Design Unit 2: Objects and Classes Faculty of Computing, Engineering and Mathematical Sciences Schedule Quick recap on Use Case diagrams UWE Flix

More information

A - 1. CS 494 Object-Oriented Analysis & Design. UML Class Models. Overview. Class Model Perspectives (cont d) Developing Class Models

A - 1. CS 494 Object-Oriented Analysis & Design. UML Class Models. Overview. Class Model Perspectives (cont d) Developing Class Models CS 494 Object-Oriented Analysis & Design UML Class Models Overview How class models are used? Perspectives Classes: attributes and operations Associations Multiplicity Generalization and Inheritance Aggregation

More information

Introduction to OO Concepts

Introduction to OO Concepts Introduction to OO Concepts Written by John Bell for CS 342, Fall 2018 Based on chapters 1, 2, and 10 of The Object-Oriented Thought Process by Matt Weisfeld, with additional material from UML Distilled

More information

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS)

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS) GETTING STARTED: YOUR FIRST JAVA APPLICATION 15 3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS) GETTING STARTED: YOUR FIRST JAVA APPLICATION Checklist: The most recent version of Java SE Development

More information

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods Main concepts to be covered Understanding class definitions Looking inside classes fields constructors methods parameters assignment statements 5.0 2 Ticket machines an external view Exploring the behavior

More information

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation Anatomy of a Method September 15, 2006 HW3 is due Today ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev Midterm 1 Next Tuesday Sep 19 @ 6:30 7:45pm. Location:

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG 1 Notice Reading Assignment Chapter 1: Introduction to Java Programming Homework 1 It is due this coming Sunday

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT Object Oriented Programming Examiner s Report March 2017 A1. a) Explain what is meant by the following terms:

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Example: Fibonacci Numbers

Example: Fibonacci Numbers Example: Fibonacci Numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers

More information

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE. Speaking the Language of OO

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE. Speaking the Language of OO PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE Speaking the Language of OO COURSE INFO Instructor : Alper Bilge TA : Gökhan Çıplak-Ahmet Alkılınç Time : Tuesdays 2-5pm Location

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

Patterns and Testing

Patterns and Testing and Lecture # 7 Department of Computer Science and Technology University of Bedfordshire Written by David Goodwin, based on the lectures of Marc Conrad and Dayou Li and on the book Applying UML and (3

More information

Chapter 11: Create Your Own Objects

Chapter 11: Create Your Own Objects Chapter 11: Create Your Own Objects Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Our usual text takes a fairly non-standard departure in this chapter. Instead, please refer

More information

Curriculum Map Grade(s): Subject: AP Computer Science

Curriculum Map Grade(s): Subject: AP Computer Science Curriculum Map Grade(s): 11-12 Subject: AP Computer Science (Semester 1 - Weeks 1-18) Unit / Weeks Content Skills Assessments Standards Lesson 1 - Background Chapter 1 of Textbook (Weeks 1-3) - 1.1 History

More information

Lecturer: Sebastian Coope Ashton Building, Room G.18 COMP 201 web-page:

Lecturer: Sebastian Coope Ashton Building, Room G.18   COMP 201 web-page: Lecturer: Sebastian Coope Ashton Building, Room G.18 E-mail: coopes@liverpool.ac.uk COMP 201 web-page: http://www.csc.liv.ac.uk/~coopes/comp201 Lecture 17 Concepts of Object Oriented Design Object-Oriented

More information

CS112 Lecture: Defining Instantiable Classes

CS112 Lecture: Defining Instantiable Classes CS112 Lecture: Defining Instantiable Classes Last revised 2/3/05 Objectives: 1. To describe the process of defining an instantiable class 2. To discuss public and private visibility modifiers. Materials:

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7 Administration Classes CS 99 Summer 2000 Michael Clarkson Lecture 7 Lab 7 due tomorrow Question: Lab 6.equals( SquareRoot )? Lab 8 posted today Prelim 2 in six days! Covers two weeks of material: lectures

More information

Comp-304 : Object-Oriented Design What does it mean to be Object Oriented?

Comp-304 : Object-Oriented Design What does it mean to be Object Oriented? Comp-304 : Object-Oriented Design What does it mean to be Object Oriented? What does it mean to be OO? What are the characteristics of Object Oriented programs (later: OO design)? What does Object Oriented

More information

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to: Get JAVA To compile programs you need the JDK (Java Development Kit). To RUN programs you need the JRE (Java Runtime Environment). This download will get BOTH of them, so that you will be able to both

More information

Computer Science II Data Structures

Computer Science II Data Structures Computer Science II Data Structures Instructor Sukumar Ghosh 201P Maclean Hall Office hours: 10:30 AM 12:00 PM Mondays and Fridays Course Webpage homepage.cs.uiowa.edu/~ghosh/2116.html Course Syllabus

More information

CS 11 java track: lecture 1

CS 11 java track: lecture 1 CS 11 java track: lecture 1 Administrivia need a CS cluster account http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi need to know UNIX www.its.caltech.edu/its/facilities/labsclusters/ unix/unixtutorial.shtml

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecture 14: Design Workflow Department of Computer Engineering Sharif University of Technology 1 UP iterations and workflow Workflows Requirements Analysis Phases Inception Elaboration

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Ray John Pamillo 1/27/2016 1 Nokia Solutions and Networks 2014 Outline: Brief History of OOP Why use OOP? OOP vs Procedural Programming What is OOP? Objects and Classes 4 Pillars

More information

Computer Science II (20082) Week 1: Review and Inheritance

Computer Science II (20082) Week 1: Review and Inheritance Computer Science II 4003-232-08 (20082) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Syntax and Semantics of Formal (e.g. Programming) Languages Syntax

More information

Where do objects come from? Good question!

Where do objects come from? Good question! Designing Classes CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Where do objects

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 1 Date:

More information

Methods and Data (Savitch, Chapter 5)

Methods and Data (Savitch, Chapter 5) Methods and Data (Savitch, Chapter 5) TOPICS Invoking Methods Return Values Local Variables Method Parameters Public versus Private 2 public class Temperature { public static void main(string[] args) {

More information

Lecture 7: Classes and Objects CS2301

Lecture 7: Classes and Objects CS2301 Lecture 7: Classes and Objects NADA ALZAHRANI CS2301 1 What is OOP? Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly

More information

1: Introduction to Object (1)

1: Introduction to Object (1) 1: Introduction to Object (1) 김동원 2003.01.20 Overview (1) The progress of abstraction Smalltalk Class & Object Interface The hidden implementation Reusing the implementation Inheritance: Reusing the interface

More information

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 1. Introduction 2. Objects and classes 3. Information hiding 4. Constructors 5. Some examples of Java classes 6. Inheritance revisited 7. The class hierarchy

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