Lecture 3. Lecture

Similar documents
News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Introduction to Programming Using Java (98-388)

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

The return Statement

Object Oriented Programming in C#

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005

Chapter 4 Defining Classes I

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

Java Identifiers, Data Types & Variables

1 Shyam sir JAVA Notes

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

COP 3330 Final Exam Review

CS121/IS223. Object Reference Variables. Dr Olly Gotel

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

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

Fall 2017 CISC124 9/16/2017

Inheritance and Interfaces

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

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

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

An introduction to Java II

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

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Example: Fibonacci Numbers

Handout 7. Defining Classes part 1. Instance variables and instance methods.

CS-201 Introduction to Programming with Java

Recursion 1. Recursion is the process of defining something in terms of itself.

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Lecture 5: Methods CS2301

Lecture 4. Lecture

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking

Pace University. Fundamental Concepts of CS121 1

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Java and OOP. Part 2 Classes and objects

PROGRAMMING FUNDAMENTALS

CS171:Introduction to Computer Science II

Primitive vs Reference

Assignment 4. Aggregate Objects, Command-Line Arguments, ArrayLists. COMP-202B, Winter 2011, All Sections. Due: Tuesday, March 22, 2011 (13:00)

CS 231 Data Structures and Algorithms, Fall 2016

Short Notes of CS201

Object Oriented Modeling

*Java has included a feature that simplifies the creation of

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

CS201 - Introduction to Programming Glossary By

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

Object-Oriented Principles and Practice / C++

STUDENT LESSON A5 Designing and Using Classes

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Object-Oriented Programming Concepts

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

11. a b c d e. 12. a b c d e. 13. a b c d e. 14. a b c d e. 15. a b c d e

Operational Semantics. One-Slide Summary. Lecture Outline

1007 Imperative Programming Part II

Definition of DJ (Diminished Java)

THE CONCEPT OF OBJECT

C++ for Java Programmers

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

CS201 Some Important Definitions

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

FORM 2 (Please put your name and form # on the scantron!!!!)

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Computer Science 1 Ah

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Java Primer 1: Types, Classes and Operators

Programming Languages and Techniques (CIS120)

CSE 401/M501 Compilers

class objects instances Fields Constructors Methods static

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Java Classes & Primitive Types

Motivation was to facilitate development of systems software, especially OS development.

G Programming Languages - Fall 2012

Praktische Softwaretechnologie

Computer Components. Software{ User Programs. Operating System. Hardware

Lecture 2, September 4

Design Patterns: State, Bridge, Visitor

Java Classes & Primitive Types

Compiler Theory. (Semantic Analysis and Run-Time Environments)

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

( &% class MyClass { }

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

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Week 8: Operator overloading

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Chapter 5. Names, Bindings, and Scopes

UNIT II Structuring the Data, Computations and Program. Kainjan Sanghavi

CE221 Programming in C++ Part 1 Introduction

Operational Semantics of Cool

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

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation

BBM 102 Introduction to Programming II Spring 2017

Transcription:

True Object-Oriented programming: Dynamic Objects Static Object-Oriented Programming Reference Variables Eckel: 30-31, 41-46, 107-111, 114-115 Riley: 5.1, 5.2 D0010E Object-Oriented Programming and Design UML knowsabout - Håkan Jonsson 1 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 1

Loops and recursion Are loops and recursion really equally powerful? Yes But it s non-trivial to prove. <= : Any recursive Java program is transformed into an iterative program by the compiler. The instruction set of computers lack recursive parts, so instead the computer simulates recursion using iteration and a stack. => : Later on in the course, I will show how any of Java s loops can be transformed into (a semantically identical) recursion. So, for any iterative program there is a recursive program that computes the same result. In practice, there are some semantic differences. For example: Infinite recursion might exhaust the stack, and cause termination after a finite number if steps, while the corresponding infinite loop does not terminate the program. But note that neither computes anything sensible in this case. - Håkan Jonsson 4 Review: Java Programs A Java program consists of source code. The source code contains at least one class. Classes are written by programmers, have names that start with an upper-case letter, and, contain declarations of attributes like variables and methods. Yet, Java is object-oriented, not class-oriented. What does this mean? - Håkan Jonsson 5 Classes versus Objects Classes exist, and are created, when a programmer writes a Java program. The classes describe objects that will/can be created once the program is executed. In practice, everything that happens in a program takes place in methods of objects. The thread of execution shifts between methods when they call each other and when methods end. Like shown in the previous lecture. The program starts when the operating system calls the method main(). A class defines a type. - Håkan Jonsson 6 2

Classes versus Objects We differ between two stages in time: Compile-time: The time during which a program is being written and then compiled. Run-time: The time during which a program is executed. There are no objects during compile-time. There is only source code being written. There are no classes during run-time. There exists only static and dynamic objects. Objects are created and exist during run-time only. - Håkan Jonsson 7 Two kinds of objects per class One static object. Contains everything in the class declared with the modifier static. Is automatically created when the program starts. Exists until the program terminates. Attribute x in the static object described by class C is referred to by C.x (Has no type.) (Old style of programming.) Today s topic Arbitrary many dynamic objects. Contain everything in the class not declared static. Are created during runtime using the keyword new. Exist as long as they can be reached via a reference chain all the way from the static main-method. Are referred to via reference variables ( pointers ). refvar.x Each class defines a type. - Håkan Jonsson 8 Classes as templates So, a class can be thought of as a type definition and a template for a set of objects. Defines what objects of the type of the class contain/can do. Right now in the course, objects contain methods and Runnable code that can be invoked. Defines behavior. variables Hold data, or refers to data. Defines state. (There is more to come.) as declared in the class. Remember: Objects are used to represent information when the computer program executes. - Håkan Jonsson 9 3

2014-01- 29 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride Example: The class A dynamic object of type represents a signal that can be turned on or off. Remember: During run-time, a program can create any number of dynamic objects. So, any number of signals can be created. The static object of the class holds statistics about all created signals. Remember: During run-time, there is exactly one static object per class (e.g. ). - Håkan Jonsson 11 public class { // declarations for the static object // of the class static int numberofs = 0; static int numberon = 0; static float percentageon() { if (numberofs == 0) { return 0f; } else { return (float) numberon / (float) numberofs; } } // declarations for dynamic objects of // type (on the next slide). - Håkan Jonsson 12 4

} public () { // this is a (the) constructor numberofs++; } boolean on = false; // holds the state, // initially off boolean ison() { // use this method to check return on; // signal status. } void seton() { if (on) { numberon++; } on = true; } void setoff() { if (on) { numberon--; } on = false; } ~numberofs : int ~numberon : int ~on : boolean ~percentageon() : float ~ison() : boolean ~seton() : void ~setoff() : void - Håkan Jonsson 13 Writing Classes Try to keep your classes in order, neat and tidy. If you like, you could for instance first list all static declarations and then all dynamic (non-static) ones. Makes it easier to understand what the static and dynamic objects contain. ~numberofs : int ~numberon : int ~on : boolean ~percentageon() : float ~ison() : boolean ~seton() : void ~setoff() : void public class ClassName { /* static declarations */ /* non-static declarations */ } Implementation Methods (etc) Variables and constants) Design UML - Håkan Jonsson 14 Constructors Dynamic objects are created by using the creation expression new and a constructor. s = new (); // s now refers to a signal A constructor contains initialization code that is executed when the object is created. In, it just increases the static variable numberofs. NB A constructor is not a method. NB A constructor has no return type nor is it void. - Håkan Jonsson 15 5

Constructors The name of a constructor must be identical to the name of the class including the capital letter in the beginning. Compare: Names of methods should start with a lower-case letter. If no constructor is declared in a class, Java adds a default constructor with no arguments. It is possible to... add parameters to constructors, which is common to do.... impose restrictions on from which code in a program objects can be created. - Håkan Jonsson 16 Overloading Constructors and methods in a class can be overloaded. X is overloaded if there are more than one declaration of X. All methods must return the same type of result. If X is overloaded, no two declarations of X may have exactly the same list of parameters. The method max can be overloaded like this: public static void max(int a, int b) public static void max(int x, int y, int z) public static void max(double u, double v) However, it is not allowed to have yet a method declared public static void max(int first, int second) since there is already a version of max with these parameters. System.out.println is an example of an overloaded method. There is one version of it for each set of parameters it is defined for. - Håkan Jonsson 17 This program creates and makes use of signals, i.e. dynamic objects of type. public class Test { public static void main(string[] args) { s1 = new (); } } s2 = new (); System.out.println(s1.isOn()); s1.seton(); System.out.println(s1.isOn()); if (s2.ison()) { s1.setoff(); s2.seton(); } System.out.println(s1.isOn()); System.out.println(s2.isOn()); System.out.println("% = " +.percentageon()); - Håkan Jonsson 18 6

Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride UML: Associations An association exists where a class knows about another class. Associations are represented by lines with arrows: A filled line means [the class] contains a [declaration of a] variable of this type. A dashed line means contains a parameter, local variable, or method returning a result of this type. A line starts at a containing class and points its arrow at the type. If the association is bidirectional, arrows are placed at both ends of the connecting line. A number at an arrow denotes multiplicity. The example to the right means: (Something in) Test has two (2) parameters/local variables/ results of type. 2 ~numberofs : int ~numberon : int ~on : boolean ~percentageon() : float ~ison() : boolean ~seton() : void ~setoff() : void - Håkan Jonsson 20 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 7

References Reference variables are used to interact with (reach) dynamic objects. The variable references, or points, at the object. A reference variable can be thought of as a road sign that can point at a dynamic object. Or be broken and not point at all (or just at the ground where it stands). Called illegal or null. Make sure you understand the difference between a road sign and what the sign points at. This is similar to the difference between a reference variable and the dynamic object referenced by the variable. t t - Håkan Jonsson 22 Example An illegal (or null) reference: Exists but doesn t point at all t t - Håkan Jonsson 23 Example s1; s2; s2 s1 Two reference variables of type are created - Håkan Jonsson 24 8

2014-01- 29 Example s1 = new (); A dynamic object of type is created... public () { // this is a (the) constructor numberofs++; } boolean on = false; // holds the state, // initially off... on == false We make s1 point at the new dynamic object (a signal ) s1 - Håkan Jonsson 25 Example s1.seton();... void seton() { if (on) { numberon++; } on = true; }... on == true Changes from false to true s1 - Håkan Jonsson 26 Example s2 = s1; on == true We make s2 point at what s1 points at s2 s1 - Håkan Jonsson 27 9

... Example s2.setoff(); void setoff() { if (on) { numberon--; } on = false; }... on == false s2 Changes back to false again s1 - Håkan Jonsson 28 Example s1 = null; on == false Changes s1 to illegal/null s2 s1 - Håkan Jonsson 29 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 10

Dynamic Objects Dynamic objects are the essence in objectoriented programming The static objects are very limited and neither necessary nor really used that much. They are not as flexible as dynamic objects and can unfortunately not be used in the same contexts. They are programmed much like old-fashioned imperative programming (c, for instance). However, we get them for free in Java. To understand how dynamic objects are used we need to go into how computer memory and variables function. - Håkan Jonsson 31... 50 1000...... 39" 40" 41" 42" 43" 44" 45" 46" 47" 48" 49" 50" 51"... Memory and the Storage of Data An integral part of a computer is its memory, which can be thought of as a (long) sequence of individual cells each of which can store a number. Each cell has a unique address. There are two basic forms of access to a cell. Direct addressing The cell at the address contains the data. Indirect addressing The cell at the address contains the address of the memory cell that contains the actual data. These two basic forms of access gives rise to two very different kinds of variables. - Håkan Jonsson 32 Variables In a program, a variable stands for the address of a memory cell. There are two kinds in Java: Primitive variables: The content of the memory cell contains data. Are stored in variable memory. Are used for integers, floating-point numbers, characters, and booleans. Reference variables: The content of the memory cell contains the address of the memory cell that contains the data. The data is stored in object memory. Used to keep track of dynamic objects. - Håkan Jonsson 33 11

Lifetime of variables The lifetime of any kind of variable spans from when it is allocated (created) until it is deallocated (destroyed). The lifetime is the period of time during which it exists. Variables that are static: Declared static so they belong to the static object. Allocated when the program starts and deallocated when the program ends. Variables that are dynamic: Declared in a class without the word static. Created when the object is created. Deallocated when the dynamic object holding the variable is deallocated. Recall that this happens when there is no longer a reference chain connecting main() and the object More on this at later lectures. - Håkan Jonsson 34 Lifetime of variables Variables that are automatic. Local variables in, and formal parameters to, methods and constructors. Temporary variables in compound statements. for (int i = 0; ) { i is alive here only } { int a; } a exists inside the pair { and }. Automatic variables live (exist) during the execution of the construct where they are created only. - Håkan Jonsson 35 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 12

Example: s We will now see how dynamic and static objects can be created and used in the context of signals and the class. The static and the dynamic objects have different functionality: A dynamic object of type represents a signal that can be turned on or off. The static object of the class holds statistics about all created signals. - Håkan Jonsson 37 The class public class { // declarations for the static object // of the class.. A (the only) dynamic variable Two static static int numberofs = 0;. variables static int numberon = 0; boolean on = false; // holds the state, // initially off static float percentageon() { if (numberofs ==0) { boolean ison() { // use this method to check A (the only) return 0f; return on; // signal status. static method } else { return (float) numberon } / (float) numberofs; } void seton() { } if (on) { // declarations for dynamic objects of numberon++; // type. } on = true; Three dynamic methods public () { A (the only) } numberofs++; constructor } void setoff() { if (on) {. numberon--;. }. ~numberofs : int on = false; ~numberon : int } ~on : boolean } ~percentageon() : float ~ison() : boolean ~seton() : void ~setoff() : void - Håkan Jonsson 38 Test using s1 and s2 are reference variables of type (pointer to) that refer to the two new signal objects Assume that we halt here during a run. false true false true % = 0.5 public class Test { public static void main(string[] args) { } } Creates two dynamic objects s1 = new (); of type s2 = new (); System.out.println(s1.isOn()); s1.seton(); System.out.println(s1.isOn()); if (s2.ison()) { s1.setoff(); Calls the method setoff in the object referred to by s1 and seton in the object s2.seton(); referred to by s2 } System.out.println(s1.isOn()); System.out.println(s2.isOn()); System.out.println("% = " +.percentageon()); - Håkan Jonsson 39 13

A snap-shot at the sbjects Dynamic objects on == false on == true s1 numberofs == 2 s2 numberon == 1 Test Static objects - Håkan Jonsson 40 Access to objects of a class Everything in the static object is accessible by all dynamic objects. The static object is referred to using the name of the class and this is known before the program is executed. Nothing in a dynamic object is available to the static object, unless the static object has a reference to the object. Not even the dynamic object itself (of course). The static object is therefore often programmed to hold data and methods common to all the dynamic objects. Important to remember: Reference variables can only refer to dynamic objects, not static objects. Access to a dynamic object requires a reference to it. - Håkan Jonsson 41 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 14

A more extensive example We like to study how far a helicopter flies when directed to travel (in straight lines) to a sequence of destinations. The type Helicopter is defined in the class Helicopter. The main program, HelicopterMain, has a reference variable h that points to a helicopter with call sign Z 41. This means there will be a filled line with an arrow in the UMLdiagram (not a dotted one). This helicopter is then requested to fly between given coordinates. Finally, we print h s callsign, currently location, and distance flown. NB The class Helicopter contain parts that are hard to understand (yes) at this point in the course and that will be the topic of upcoming lectures. package l03.ex2; public class HelicopterMain { public static Helicopter h = new Helicopter("Z 41"); public static void main(string[] args) { h.flyto(65, 40); h.flyto(-43, 74); System.out.println(h.callSign() + " is at (" + h.getx() + ", + h.gety() + ") and has flown " + h.distanceflown() + " km."); } } 1 HelicopterMain Helicopter package l03.ex2; public class Helicopter { private String callsign = ""; private long rtx = 0L, rty = 0L; private double distanceflown = 0.0d; public Helicopter(String name) { callsign = name; } public void flyto(long x, long y) { double dx = Math.abs(x - rtx); double dy = Math.abs(y - rty); distanceflown += Math.sqrt(dx * dx + dy * dy); rtx = x; rty = y; } public String callsign() { return callsign; } public long getx() { return rtx; } public long gety() { return rty; } public double distanceflown() { return distanceflown; } } Prints: Z 41 is at (-43,74) and has flown 189.54712645011404 km. Another snap-shot at objects Helicopter callsign== Z 41 rtx == -43 rty == 74 distanceflown == 189.54712645011404 h Helicopter HelicopterMain - Håkan Jonsson 45 15

Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 16