Download presentation
Presentation is loading. Please wait.
1
CompSci 230 Software Construction
Lecture Slides #3: Introduction to OOD S1 2016
2
Agenda Topics: Software Design (vs. hacking)
Object-Oriented Design (vs. other approaches to SW design) Classes & Objects Introduction to UML class diagrams Object diagrams may be helpful for visualizing instantiations Variables & Methods COMPSCI 230: IOOD
3
Software Design Communication: Planning: Modeling Construction:
Identify stakeholders, find out what they want and need. Planning: List tasks, identify risks, obtain resources, define milestones, estimate schedule. Modeling Develop structure diagrams and use cases, maybe some other UML artifacts. Different approaches: OO, procedural, data. Construction: Implement the software, with assured quality. Deployment: Deliver the software, then get feedback for possible revision. To learn more: R. Pressman, Software Engineering: A Practitioner’s Approach, 7th Ed., 2010, pp COMPSCI 230: IOOD
4
What is Object-Oriented Design?
In OO design, a system is a collection of interacting objects. Each object should have simple attributes and behaviours. Each object should have simple relations to other objects. In procedural design, a system is a collection of basic blocks. Each basic block should have a simple effect on local and global variables. Basic blocks are linked by control- flow arcs: if/then/else, call/return, while/loop, for/loop, case, goto, … In data architecture, a system is a collection of data structures, with access and update methods. Each data structure should have simple relations to other data structures. object 3 object 2 object 4 object 1 Program COMPSCI 230: IOOD
5
What is an Object? A building block for OO development Examples:
Like objects in the world around us Objects have state and behaviour Examples: Dog State/field/attribute: name, colour, isHungry, … Behaviour: sit(), down(), come(), … Bicycle State: gear, cadence, colour, … Behaviour: brake(), turn(), changeGear(), … VCR State: brand, colour, isOn … Behaviour: play(), stop(), rewind(), turnOn(), … COMPSCI 230: IOOD
6
Classes & Objects Class Object
A set of objects with shared behaviour and individual state Individual state: Data is stored with each instance, as an instance variable. Shared behaviour: Code is stored with the class object, as a method. Shared state may be stored with the class object, as a class variable. Object Objects are created from classes at runtime by instantiation usually with new. There may be zero, one, or many objects (instances) of a class. Instantiated objects in Java are garbage-collected if no other user-defined object references them.
7
Example: A simple Java class
public class SimpleCounter { public int counterValue; public int count() { return ++counterValue; } Instance variable (the value of the counter) This value is different for each instance (object) of the class that we create (i.e., we can have many counters) Method (behaviour) (increment the counter) The method operates on an instance variable, so is an instance method. (=we can only invoke it on an object, not on the class itself) It does not take a parameter but returns an integer to the calling code (caller). COMPSCI 230: IOOD
8
Example: Using our simple Java class
Console output: public class SimpleCounter { public int counterValue; public int count() { return ++counterValue; } Value of c1.counterValue: 2 Value of c2.counterValue: 1 public class SimpleCounterProgram { public static void main(String[] args) { SimpleCounter c1 = new SimpleCounter(); // instantiate a simple counter c1.counterValue = 0; SimpleCounter c2 = new SimpleCounter(); // instantiate another simple counter c2.counterValue = 0; c1.count(); c2.count(); System.out.println("Value of c1.counterValue: " + c1.counterValue); System.out.println("Value of c2.counterValue: " + c2.counterValue); } COMPSCI 230: IOOD
9
Example: Using our simple Java class
Console output: public class SimpleCounter { public int counterValue; public int count() { return ++counterValue; } Value of c1.counterValue: 2 Value of c2.counterValue: 1 main() method public class SimpleCounterProgram { public static void main(String[] args) { SimpleCounter c1 = new SimpleCounter(); // instantiate a simple counter c1.counterValue = 0; SimpleCounter c2 = new SimpleCounter(); // instantiate another simple counter c2.counterValue = 0; c1.count(); c2.count(); System.out.println("Value of c1.counterValue: " + c1.counterValue); System.out.println("Value of c2.counterValue: " + c2.counterValue); } The type of c1 and c2 is SimpleCounter (the class) Instantiation with new COMPSCI 230: IOOD
10
Our simple objects at the end of execution
c1: SimpleCounter counterValue = 2 c2: SimpleCounter counterValue = 1 COMPSCI 230: IOOD
11
Imagine a world of communicating objects
An object remembers things (i.e. it has a memory): its state. E.g., counter value in the SimpleCounter class An object responds to messages it gets from other objects. It performs the method with the given parameters (if any), then sends a response. E.g., count() returns the incremented counter value in the SimpleCounter class An object that receives a strange message may throw an exception. Be careful not to trigger exceptions by mistake! An object’s method may “ask for help” from other objects. It sends a message to an object, and waits for a response. E.g.: call a method of another object. A method may also send a message to itself! This is called recursion. Be careful: If a method calls itself, it may never return (stack overflow) Messages between objects Usually: method calls and method returns, sometimes exceptions. COMPSCI 230: IOOD
12
Messaging by method Example: someVariable = myObject.someMethod(someParameterValue); Response Receiver (receiving object) Message (method) Message parameters (method parameters) Typically, we expect the code above to be located in a method of another object (the sender). COMPSCI 230: IOOD
13
This looks like a method call - and indeed it is!
Constructors Look at SimpleCounter again: This is how we instantiate and initialize it: SimpleCounter c1 = new SimpleCounter(); c1.counterValue = 0; Do we really need the second line? When we instantiate an object of a class, we implicitly call the constructor method of the class public class SimpleCounter { public int counterValue; public int count() { return ++counterValue; } This looks like a method call - and indeed it is! COMPSCI 230: IOOD
14
Constructors public class SimpleCounter { public int counterValue; public int count() { return ++counterValue; } If we don’t declare a constructor in the class, the compiler will insert a default constructor. This just so happens to initialise instance variables declared as int to 0, but this is something we shouldn’t rely on. Alternative: use an explicit constructor: public class SimpleInitialisedCounter { public int counterValue; public SimpleInitialisedCounter() { counterValue = 0; } public int count() { return ++counterValue; COMPSCI 230: IOOD
15
Notes on constructors in Java
A constructor is always public The name of the constructor is the same as the class The constructor gets invoked when the object is instantiated (read: built based on the “blueprint” that the class provides) Does not use a return type (it returns an object whose type is the class, which is sort of obvious!) We can pass parameters to constructors in the same way as any other method E.g., to initialise instance variables COMPSCI 230: IOOD
16
Overloading constructors
These two constructors differ in the number of parameters: public class SimpleInitialisableCounter { public int counterValue; public SimpleInitialisableCounter() { counterValue = 0; } public SimpleInitialisableCounter(int initialValue) { counterValue = initialValue; public int count() { return ++counterValue; SimpleInitialisableCounter ca = new SimpleInitialisableCounter(); // start counter at 0 SimpleInitialisableCounter cb = new SimpleInitialisableCounter(42); // start counter at 42 COMPSCI 230: IOOD
17
ca: SimpleInitialisableCounter cb: SimpleInitialisableCounter
Object Instantiation Calling a constructor method creates a new instance of the class: The variables ca and cb hold a reference to the objects We can think of a reference as being the address of the object in memory In Java, references do a little bit more: the Java VM keeps track of all variables that reference an object. This assists in garbage collection. SimpleInitialisableCounter ca = new SimpleInitialisableCounter(); // start counter at 0 SimpleInitialisableCounter cb = new SimpleInitialisableCounter(42); // start counter at 42 ca: SimpleInitialisableCounter SimpleInitialisableCounter = 0 cb: SimpleInitialisableCounter SimpleInitialisableCounter = 42 COMPSCI 230: IOOD
18
Java Garbage Collection
Each time we instantiate an object, the Java VM requests memory from the operating system and makes it available to the program to store the object in memory. The program can work with the object as long as it has a reference to the object (the object’s address, basically) An object can be referenced by more than one variable in a program – it’s like keeping multiple copies of the same address When all references to an object are lost, the object is still in memory but the program can no longer interact with it This typically happens when the variables holding a reference are overwritten, or go out of scope at the end of a method Think of it like owning a house but having lost all records of its address – the house continues to exist but you can’t do anything with it! The Java VM keeps track of the number of references a program maintains for an object. If this number goes to 0, the object is tagged for garbage collection. Garbage collection runs periodically and returns the memory of tagged objects to the operating system, so other programs can use it. In languages without garbage collection (e.g., C,/C++), programs instantiating objects on an ongoing basis consume an increasing amount of memory (aka “memory leak”) unless they explicity free the memory again when it is surplus to requirements. COMPSCI 230: IOOD
19
Information Hiding Look at the SimpleCounter class again:
Note how we can both set and read the counterValue on objects of type SimpleCounter at any time? What if we don’t want other code to be able to set the value? E.g., think of a car odometer: you don’t want people to be able to wind it back before they sell you the car In software, we often encounter similar situations where we don’t want other code to set values directly public class SimpleCounter { public int counterValue; public int count() { return ++counterValue; } COMPSCI 230: IOOD
20
This code won’t work now in another class:
Information Hiding Make instance variables private to hide them from code outside the class itself: The count() method lets us increment and retrieve the counterValue Exercise: add a getCounterValue() instance method to the class that retrieves the counterValue public class OneWayCounter { private int counterValue; public OneWayCounter() { counterValue = 0; // initialise the counter when it is created } public int count() { return ++counterValue; This code won’t work now in another class: OneWayCounter c = new OneWayCounter(); c.counterValue = 10; Not visible! COMPSCI 230: IOOD
21
Information hiding techniques
Instead of making instance variables public, make them private Add methods to the class that can write or read these variables Such methods are called “setters” (write) and “getters” (read) Advantage: can add code to these methods to make something else happen when we read or write the value of the field Example: When we write to the field that stores the colour of a graphical object on the screen, we usually also want to re-paint the object in the new colour Example: We may wish to compute the value that we read at the time that we read it. E.g., have fields that store width and length of a rectangle, and use a getter to compute its area as width*length. Advantage: can add / repair functionality in setter and getter later as code from other classes cannot access the field directly anymore – so the other code cannot circumvent the functionality Can use a setter without a getter and vice versa E.g., don’t need a setter for the area of a rectangle (what should it change, anyway: width or length or both?) Information hiding is also known as encapsulation COMPSCI 230: IOOD
22
OO Review Part 1 Class: the “blueprint” or “construction plan” for building an actual object. Objects of the class are also known as instances of the class. When we create such an object, we say that we instantiate the class. However, classes are also objects themselves so can store data and contain methods. In Java, we recognize such class variables and class methods from their declaration with the keyword static A class is also a type (like int or double): It is the type of the variables, method parameters and method return values that reference objects of that class. Any variables or methods (whether static or not) declared inside a class are known as members of the class In Java, there is no code outside a class COMPSCI 230: IOOD
23
OO Review Part 2 Object: a data structure built according to the declarations in a class. Variables (static or not) declared inside the class are accessible (read and write) from code within objects of the class. Such variables are also often referred to as fields. If a variable is not declared as static (i.e., it is not a class variable), it is called an instance variable. Instance variables are not shared between objects. Variables that “store” objects actually only store a reference to the object (i.e., basically the object’s location in memory) If we “store” the same object in two or more variables, we do not copy the object itself. Only one object remains, but we now have several references to it. If a program has an existing object, but no variable in the program refers to it any more, the program can no longer access the object. If the language used does not perform garbage collection, this results in a memory leak (memory allocated to, but no longer controlled by the program) COMPSCI 230: IOOD
24
OO Review Part 3 Instance variable: A variable that is not shared between different objects of the same class. E.g., if we have a class that declares an instance variable x, and two objects A and B of that class, then setting A.x will not affect the value of B.x and vice versa. Class variable: A variable that is shared between all objects of the same class. E.g., if we have a class that declares an class (static) variable x, and two objects A and B of that class, then setting A.x will also change the value of B.x and vice versa. COMPSCI 230: IOOD
25
OO Review Part 4 Method: A function declared in a class. They can also be thought of as types of messages that the class (or an object of the class may receive), and as a mechanism for the class (or object) to respond to these messages. Methods may take parameters. In Java, these parameters must each be declared and given a type. Code that invokes a method must supply parameters of that type. Methods may return a value (the return value). In Java, the type of that value must be declared along with the method itself. A method that does not return a value is declared as void. Methods may be overloaded. Overloaded methods share the same name but differ in number and/or type(s) of parameters and/or type of return value. In code calling the method, the compiler works out the return type required and the number / types of parameters offered and determines the required version of the method. (Note: In Java, methods cannot be overloaded based on return type only) Methods may be static or not. Static methods (aka class methods) can only operate on static variables (aka class variables). Non-static methods (aka instance methods) can operate on both class variables and instance variables. COMPSCI 230: IOOD
26
OO Review Part 5 Constructor: A special method which is automatically invoked when an object is instantiated (created based on the class) In Java: When a class does not explicitly declare a constructor, Java automatically calls a default constructor. In Java: We can pass parameters to a constructor, but we do not declare a return value (the return value is always the object, the return type is the class) In Java: We can overload constructors like any other method. COMPSCI 230: IOOD
27
OO Review Part 6 Setter: A method that takes a single parameter and “sets” the value of an object property. This value is usually stored in a private field of the object. Getter: A method that takes no parameter and “gets” the value of an object property. This value is usually read from a private field of the object. Can use setters and getters to implement additional actions to be taken when setting and reading the value of the private field. N.B.: If the actions are all we need, then we may not need the private field. Can implement setter without getter and vice versa (“read-only” property) In Java: convention has it that if the property has name X, the setter will be called setX() and the getter will be called getX(). COMPSCI 230: IOOD
28
OO Review Part 7 private: visibility modifier in Java (and other OO languages). If it precedes a method, it specifies that this method can only be invoked by other methods in the same class (note: this generally includes instance methods of other objects of the same class). If it precedes a variable (class or instance), it specifies that the variable can only be used by methods in the same class (note: in the case of instance variables, this generally includes instance methods of other objects of the same class). public: visibility modifier in Java (and other OO languages). If it precedes a method, it specifies that this method can be invoked by any other method in this or other classes. If it precedes a variable, it specifies that this variable can be set and read by any other method in this or other classes. Note that this is often undesirable (see setters and getters). COMPSCI 230: IOOD
29
Revision questions Why is the main() method that starts a program declared as static? How would you implement a read-only field? When do we invoke a constructor? How does a compiler work out which version of an overloaded method you want to use? What is the difference between an instance method and a class method? Which sort of variable is not shared between object of the same class? How do you instantiate a class C with a constructor that takes an integer parameter and a String parameter (say you want them to have values 230 and “software”)? COMPSCI 230: IOOD
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.