CompSci 230 Software Construction

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

Road Map Introduction to object oriented programming. Classes
1 Classes Overview l Classes as Types l Declaring Instance Variables l Implementing Methods l Constructors l Accessor and Mutator Methods.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Object Oriented Software Development
Lecture 1 Introduction to Software Construction
Programming Languages and Paradigms Object-Oriented Programming.
Java Classes Using Java Classes Introduction to UML.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Introduction to Object-Oriented Programming Lesson 2.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Topics Instance variables, set and get methods Encapsulation
CompSci 230 S Software Construction Introduction to OOD.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Comp1004: Building Better Objects II Encapsulation and Constructors.
Memory Management.
CompSci 230 S Programming Techniques
Introduction to Object-oriented Programming
Topic: Classes and Objects
Classes and Objects Introduced
Classes and Objects.
Static data members Constructors and Destructors
Classes and OOP.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Lecture 5: Some more Java!
Lecture 6: Object-Oriented Design, Part 3
Lecture 6 D&D Chapter 7 & 8 Intro to Classes and Objects Date.
Methods Attributes Method Modifiers ‘static’
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
Road Map Introduction to object oriented programming. Classes
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
CompSci 230 Software Construction
Class Variables We’ve seen how to add extra subroutines into our programs Can be accessed from within one another We can also add variables that are “global”
Lecture 23 Polymorphism Richard Gesick.
Java LESSON 7 Objects, Part 1
Introduction to Classes
Chapter 4: Writing classes
Lecture 22 Inheritance Richard Gesick.
Encapsulation and Constructors
Chapter 9 Objects and Classes
Dr. Bhargavi Dept of CS CHRIST
Object Oriented Programming in java
Java Programming Language
Dr. R Z Khan Handout-3 Classes
References Revisted (Ch 5)
CMSC 202 Exceptions.
Lecture 1 Introduction to Software Construction
Classes and Objects Object Creation
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
(4 – 2) Introduction to Classes in C++
Creating and Using Classes
CMSC 202 Constructors Version 9/10.
Presentation transcript:

CompSci 230 Software Construction Lecture Slides #3: Introduction to OOD S1 2016

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

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. 14-15. COMPSCI 230: IOOD

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

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

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.

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

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

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

Our simple objects at the end of execution c1: SimpleCounter counterValue = 2 c2: SimpleCounter counterValue = 1 COMPSCI 230: IOOD

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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