Lecture 3. Lecture

Size: px
Start display at page:

Download "Lecture 3. Lecture"

Transcription

1 True Object-Oriented programming: Dynamic Objects Static Object-Oriented Programming Reference Variables Eckel: 30-31, 41-46, , 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

2 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

3 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

4 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

5 } 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

6 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

7 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

8 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

9 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

10 ... 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

11 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 " 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

12 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

13 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

14 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

15 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 km. Another snap-shot at objects Helicopter callsign== Z 41 rtx == -43 rty == 74 distanceflown == h Helicopter HelicopterMain - Håkan Jonsson 45 15

16 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

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

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.! True object-oriented programming: Dynamic Objects Reference Variables D0010E Object-Oriented Programming and Design Lecture 3 Static Object-Oriented Programming UML" knows-about Eckel: 30-31, 41-46, 107-111,

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

The return Statement

The return Statement The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return

More information

Object Oriented Programming in C#

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

More information

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

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Lecture - 20 Intermediate code generation Part-4 Run-time environments

More information

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

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005 Lecture 8 Classes and Objects Part 2 MIT AITI June 15th, 2005 1 What is an object? A building (Strathmore university) A desk A laptop A car Data packets through the internet 2 What is an object? Objects

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

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

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

Java Identifiers, Data Types & Variables

Java Identifiers, Data Types & Variables Java Identifiers, Data Types & Variables 1. Java Identifiers: Identifiers are name given to a class, variable or a method. public class TestingShastra { //TestingShastra is an identifier for class char

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

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

COP 3330 Final Exam Review

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

More information

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

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

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

More information

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative

More information

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Fall 2017 CISC124 9/16/2017

Fall 2017 CISC124 9/16/2017 CISC124 Labs start this week in JEFF 155: Meet your TA. Check out the course web site, if you have not already done so. Watch lecture videos if you need to review anything we have already done. Problems

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

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

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

More information

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

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list } Linked Lists Since a variable referencing an object just holds the address of the object in memory, we can link multiple objects together to form dynamic lists or other structures. In our case we will

More information

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

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012) COE318 Lecture Notes: Week 3 1 of 8 COE318 Lecture Notes Week 3 (Week of Sept 17, 2012) Announcements Quiz (5% of total mark) on Wednesday, September 26, 2012. Covers weeks 1 3. This includes both the

More information

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

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

An introduction to Java II

An introduction to Java II An introduction to Java II Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf. http://mindview.net/books/tij4 jvo@ualg.pt José Valente de Oliveira 4-1 Java: Generalities A little

More information

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.

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. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

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

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226 Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters

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

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

Handout 7. Defining Classes part 1. Instance variables and instance methods. Handout 7 CS180 Programming Fundamentals Spring 15 Page 1 of 8 Handout 7 Defining Classes part 1. Instance variables and instance methods. In Object Oriented programming, applications are comprised from

More information

CS-201 Introduction to Programming with Java

CS-201 Introduction to Programming with Java CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture X: Methods II Passing Arguments Passing Arguments methods can accept outside information

More information

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

Recursion 1. Recursion is the process of defining something in terms of itself. Recursion 1 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is repetition

More information

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

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1 A First Look At Java Didactic Module 13 Programming Languages - EEL670 1 Outline Thinking about objects Simple expressions and statements Class definitions About references and pointers Getting started

More information

Lecture 5: Methods CS2301

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

More information

Lecture 4. Lecture

Lecture 4. Lecture Interfaces Classes Building blocks Methods Arrays Example: BitArray Packages D0010E Object- Oriented Programming and Design InformaGon hiding Graphics and interacgon Example: A blinking signal Access Modifiers

More information

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

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking CSE450 Translation of Programming Languages Lecture 11: Semantic Analysis: Types & Type Checking Structure Project 1 - of a Project 2 - Compiler Today! Project 3 - Source Language Lexical Analyzer Syntax

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

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

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on

More information

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

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

Java and OOP. Part 2 Classes and objects

Java and OOP. Part 2 Classes and objects Java and OOP Part 2 Classes and objects 1 Objects OOP programs make and use objects An object has data members (fields) An object has methods The program can tell an object to execute some of its methods

More information

PROGRAMMING FUNDAMENTALS

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

More information

CS171:Introduction to Computer Science II

CS171:Introduction to Computer Science II CS171:Introduction to Computer Science II Department of Mathematics and Computer Science Li Xiong 9/7/2012 1 Announcement Introductory/Eclipse Lab, Friday, Sep 7, 2-3pm (today) Hw1 to be assigned Monday,

More information

Primitive vs Reference

Primitive vs Reference Primitive vs Reference Primitive types store values Reference types store addresses This is the fundamental difference between the 2 Why is that important? Because a reference type stores an address, you

More information

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

Assignment 4. Aggregate Objects, Command-Line Arguments, ArrayLists. COMP-202B, Winter 2011, All Sections. Due: Tuesday, March 22, 2011 (13:00) Assignment 4 Aggregate Objects, Command-Line Arguments, ArrayLists COMP-202B, Winter 2011, All Sections Due: Tuesday, March 22, 2011 (13:00) You MUST do this assignment individually and, unless otherwise

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

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Object Oriented Modeling

Object Oriented Modeling Object Oriented Modeling Object oriented modeling is a method that models the characteristics of real or abstract objects from application domain using classes and objects. Objects Software objects are

More information

*Java has included a feature that simplifies the creation of

*Java has included a feature that simplifies the creation of Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments. This feature is called as varargs (short for variable-length arguments). A method that

More information

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

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d) CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

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

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

STUDENT LESSON A5 Designing and Using Classes

STUDENT LESSON A5 Designing and Using Classes STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of

More information

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

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

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

double d0, d1, d2, d3; double * dp = new double[4]; double da[4]; All multiple choice questions are equally weighted. You can generally assume that code shown in the questions is intended to be syntactically correct, unless something in the question or one of the answers

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

Object-Oriented Programming Concepts

Object-Oriented Programming Concepts Object-Oriented Programming Concepts Object-oriented programming מונחה עצמים) (תכנות involves programming using objects An object ) represents (עצם an entity in the real world that can be distinctly identified

More information

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

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

More information

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

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 CS-3160 Concepts of Programming Languages Spring 2015 EXAM #1 (Chapters 1-6) Name: SCORES MC: /75 PROB #1: /15 PROB #2: /10 TOTAL: /100 Multiple Choice Responses Each multiple choice question in the separate

More information

Operational Semantics. One-Slide Summary. Lecture Outline

Operational Semantics. One-Slide Summary. Lecture Outline Operational Semantics #1 One-Slide Summary Operational semantics are a precise way of specifying how to evaluate a program. A formal semantics tells you what each expression means. Meaning depends on context:

More information

1007 Imperative Programming Part II

1007 Imperative Programming Part II Agenda 1007 Imperative Programming Part II We ve seen the basic ideas of sequence, iteration and selection. Now let s look at what else we need to start writing useful programs. Details now start to be

More information

Definition of DJ (Diminished Java)

Definition of DJ (Diminished Java) Definition of DJ (Diminished Java) version 0.5 Jay Ligatti 1 Introduction DJ is a small programming language similar to Java. DJ has been designed to try to satisfy two opposing goals: 1. DJ is a complete

More information

THE CONCEPT OF OBJECT

THE CONCEPT OF OBJECT THE CONCEPT OF OBJECT An object may be defined as a service center equipped with a visible part (interface) and an hidden part Operation A Operation B Operation C Service center Hidden part Visible part

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

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

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

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

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003 1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 7, 2003 Name: Email Address: TA: Section: You have 90 minutes to complete this exam. For coding questions, you do not need to

More information

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

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() { Scoping, Static Variables, Overloading, Packages In this lecture, we will examine in more detail the notion of scope for variables. We ve already indicated that variables only exist within the block they

More information

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

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam 2: FORM 2 (Please put your name and form # on the scantron!!!!) True (A)/False(B) (2 pts each): 1. Recursive algorithms tend to be less efficient than iterative algorithms. 2. A recursive function

More information

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

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations. Data Structures 1 Data structures What is a data structure? Simple answer: a collection of data equipped with some operations. Examples Lists Strings... 2 Data structures In this course, we will learn

More information

Computer Science 1 Ah

Computer Science 1 Ah UNIVERSITY OF EDINBURGH course CS0077 COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS Computer Science 1 Ah Resit Examination Specimen Solutions Date: Monday 1st September 2003 Time: 09:30 11:00

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 21 March 12, 2018 Java: Objects, Interfaces, Static Members Chapters 19 & 20 Announcements Java Bootcamp Tonight!! Towne 100, 6-8 pm HW06: Pennstagram

More information

CSE 401/M501 Compilers

CSE 401/M501 Compilers CSE 401/M501 Compilers Code Shape II Objects & Classes Hal Perkins Autumn 2018 UW CSE 401/M501 Autumn 2018 L-1 Administrivia Semantics/type check due next Thur. 11/15 How s it going? Reminder: if you want

More information

class objects instances Fields Constructors Methods static

class objects instances Fields Constructors Methods static Class Structure Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance variables)that hold the data for each object Constructors that

More information

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

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others COMP-202 Recursion Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2 Recursive Definitions (1) A recursive definition is

More information

Java Classes & Primitive Types

Java Classes & Primitive Types Java Classes & Primitive Types Rui Moreira Classes Ponto (from figgeom) x : int = 0 y : int = 0 n Attributes q Characteristics/properties of classes q Primitive types (e.g., char, byte, int, float, etc.)

More information

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

Motivation was to facilitate development of systems software, especially OS development. A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level

More information

Praktische Softwaretechnologie

Praktische Softwaretechnologie Praktische Softwaretechnologie Lecture 2. Károly Bósa () Research Institute for Symbolic Computation (RISC) 1 Books James Gosling, Bill Joy, Guy Steele The JavaTM Language Specification 2 Books James Gosling,

More information

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

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

Design Patterns: State, Bridge, Visitor

Design Patterns: State, Bridge, Visitor Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement

More information

Java Classes & Primitive Types

Java Classes & Primitive Types Java Classes & Primitive Types Rui Moreira Classes Ponto (from figgeom) x : int = 0 y : int = 0 n Attributes q Characteristics/properties of classes q Primitive types (e.g., char, byte, int, float, etc.)

More information

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

Compiler Theory. (Semantic Analysis and Run-Time Environments) Compiler Theory (Semantic Analysis and Run-Time Environments) 005 Semantic Actions A compiler must do more than recognise whether a sentence belongs to the language of a grammar it must do something useful

More information

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

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators, Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators, Expressions, Statements and Arrays. Java technology is: A programming

More information

( &% class MyClass { }

( &% class MyClass { } Recall! $! "" # ' ' )' %&! ( &% class MyClass { $ Individual things that differentiate one object from another Determine the appearance, state or qualities of objects Represents any variables needed for

More information

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

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

More information

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

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University Semantic Analysis CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Role of Semantic Analysis Syntax vs. Semantics: syntax concerns the form of a

More information

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

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I Polynomial Class Polynomial(); Polynomial(const string& N, const vector& C); Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const

More information

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

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Week 8: Operator overloading

Week 8: Operator overloading Due to various disruptions, we did not get through all the material in the slides below. CS319: Scientific Computing (with C++) Week 8: Operator overloading 1 The copy constructor 2 Operator Overloading

More information

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

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Java We will be programming in Java in this course. Partly because it is a reasonable language, and partly because you

More information

Chapter 5. Names, Bindings, and Scopes

Chapter 5. Names, Bindings, and Scopes Chapter 5 Names, Bindings, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Scope Scope and Lifetime Referencing Environments Named Constants 1-2 Introduction Imperative

More information

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

UNIT II Structuring the Data, Computations and Program. Kainjan Sanghavi UNIT II Structuring the Data, Computations and Program B y Kainjan Sanghavi Contents Monomorphic versus polymorphic type systems Case Study- The type structure of C++ and Java Structuring the computation

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

Operational Semantics of Cool

Operational Semantics of Cool Operational Semantics of Cool Key Concepts semantics: the meaning of a program, what does program do? how the code is executed? operational semantics: high level code generation steps of calculating values

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

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation Assigned: Sunday, November 14, 2004 Due: Thursday, Dec 9, 2004, at 11:59pm No solution will be accepted after Sunday, Dec 12,

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Classes and Objects in Java Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi TAs: Selma Dilek, Selim Yılmaz, Selman Bozkır 1 Today Defining

More information