CS 112 Introduction to Programming

Size: px
Start display at page:

Download "CS 112 Introduction to Programming"

Transcription

1 CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: Admin q PS6 (Sukoku) questions q Friday s class 2 1

2 Recap: Design and Implementation Methodology: Procedural Based q Design (goal oriented) top-down stepwise goal-driven method decomposition methods designed are those needed for the current goal verb driven q Program implementation and testing bottom-up 3 Recap: Design and Implementation Methodology: Object-Oriented q Design Identify objects that are part of the problem domain or solution Each object has state (variables) Each object has behaviors (methods) Often do not consider one specific goal, but rather a context noun driven 4 2

3 Side-by-Side Comparison Func%on- oriented public class DrawRocket{ public static void main(string args[]){ for (int size = 3; size < 10; size++){ drawrocket(size); public static void drawrocket(int scale){ printcap(scale); public static void printcap(int scale){... Object- oriented public class RocketDrawing{ public static void main(string args[]){ for (int size = 3; size < 10; size++){ Rocket currocket = new Rocket(size); currocket.draw(); public class Rocket{ public int rocketsize; public Rocket(int rocketsize){ this.rocketsize = rocketsize; public void draw(){ printcap(); public void printcap(){... 5 Recap: Class Definition Components Variables fields (instance variables per object) static variables (shared by all objects) Methods static methods (method usable with or without object) Can access only static variables instance methods (can be used only on objects; can access both static and instance variables) Constructors Accessors (do not change object state) Mutators (modify object state) 6 3

4 Point class: Variables public class Point { // fields (instance variables, attributes) int x; int y; // static variables shared by all objects static int numpoints = 0; Point class: Constructors public class Point { // constructors public Point(int x, int y) { this.x = x; this.y = y; numpoints ++; // a shared variable to // keep track of all // Points created. public Point() { this(0, 0); 4

5 Point class: Static Methods public class Point { // static methods: // cannot access any instance variables // because one may call Point.readpoint(input) // which has no implicit parameter public static Point readpoint(scanner scan) { Point p = new Point(); p.x = scan.nextint(); p.y = scan.nextint(); return p; public static int totalpoints() { return numpoints; Point class: Instance Methods // mutators public void translate(int dx, int dy) { x = x + dx; y = y + dy; public void setlocation(int x, int y) { this.x = x; this.y = y; // accessors public double distancefromorigin() { return Math.sqrt(x * x + y * y); public String tostring() { return "(" + x + ", " + y + ") ; public void draw() { StdDraw.filledCircle(x, y, 3); StdDraw.textLeft(x, y, tostring() ); 5

6 Point class as blueprint Point class state: int x, y behavior: translate(int dx, int dy) draw() Point object #1 state: x = 5, y = -2 behavior: translate(int dx, int dy) draw() Point object #2 state: x = -245, y = 1897 behavior: translate(int dx, int dy) draw() Point object #3 state: x = 18, y = 42 behavior: translate(int dx, int dy) draw() The class (blueprint) will describe how to create objects. Each object will contain its own data and methods. Outline q Admin and recap q Defining classes o Motivation and basic syntax Ø Examples 12 6

7 Design and Implementation Methodology: Object-Oriented Design Identify objects (nouns) and their behaviors Often do not consider one specific goal, but rather a context Often lead to more reusable, extensible software 13 Example 1: A Coin Class We define a Coin class to model a coin in heads-tails games Design questions: State: what field(s) do we need to represent the state of a coin? face, an integer (or boolean) that represents the current face Operations: what are some common behaviors/operations of a coin in a game context? a Coin constructor, to set up the object a isheads method, to return if face is HEADS a tostring method, to return a string description of the current state a flip method, to flip the coin Q: introduce a setface() method? See Coin.java, CountFlips.java, FlipRace.java 14 7

8 Instance Data: The Two Coins in FlipRace class Coin coin1: Coin int face; face = 0 coin2: Coin face = 1 15 Example 2: The BankAccount Class We define an BankAccount class to model a bank account Design questions: State: what field(s) do we need to represent the state of a bank acct? acctnumber,an integer acctname, a string balance, an integer Behaviors/operations: what are some common behaviors of a bank account in a simple banking context? A constructor, to set up the object a getbalance method, to return balance a tostring method, to return a string description of the current state a withdraw method, to withdraw from the account a deposit method, to deposit into the account a addinterest method, to add interest See BankAccount.java, Transactions.java 16 8

9 Example 2: Account and Transactions public class BankAccount { final double RATE = 0.035; long acctnumber; String acctname; double balance; public BankAccount (String owner, long account, double initial) { acctname = owner; acctnumber = account; balance = initial; public static void main (String[] args) { BankAccount aliceacct = new BankAccount ( Alice", 11111, ); BankAccount bobacct = new BankAccount ( Bob", 22222, ); BankAccount charlesacct = new BankAccount ( Charles", 33333, ); bobacct.deposit (30.00); public double deposit (double amount) { balance = balance + amount; return balance; 17 Example 2: The Three BankAccount Objects in Transactions aliceacct: BankAccount acctnumber = acctname = Alice balance = aliceacct: BankAccount acctnumber = acctname = Alice balance = bobacct: BankAccount acctnumber = acctname = Bob balance = bobacct: BankAccount acctnumber = acctname = Bob balance = charlesacct: BankAccount acctnumber = acctname = Charles balance = charlesacct: BankAccount acctnumber = acctname = Charles balance = After bobacct.deposit (30.00); 18 9

10 Example 3: The Ball Class We define a Ball class to model self-bouncing balls 19 Example 3: The Ball Class Design questions: State: what field(s) do we need to represent the state of a selfbouncing ball? rx, ry, current position vx, vy, speed color, current color left, right, bottom, top:cage (boundaries) Behaviors/operations: what are some common behaviors of a selfbouncing ball? A default constructor, to set up a random ball in unit square A constructor, to set up a ball with given parameters A move method, to update position A draw method, to display See Ball.java, BouncingBalls.java 20 10

11 Example 3: Bouncing Ball in Unit Square public class Ball { double rx, ry; double vx, vy; double radius; instance variables public Ball() { rx = ry = 0.5; vx = Math.random() * 0.03; vy = Math.random() * 0.03; radius = Math.random() * 0.01; Ball.java constructor public void move() { if ((rx + vx > 1.0) (rx + vx < 0.0)) vx = -vx; if ((ry + vy > 1.0) (ry + vy < 0.0)) vy = -vy; rx = rx + vx; ry = ry + vy; bounce public void draw() { StdDraw.filledCircle(rx, ry, radius); methods Object References q Allow client to manipulate an object as a single entity. q Essentially a machine address (pointer). Ball b1 = new Ball(); Ball b2 = new Ball(); b2 = b1; addr value main memory (64- bit machine) 11

12 Object References q Allow client to manipulate an object as a single entity. q Essentially a machine address (pointer). Ball b1 = new Ball(); Ball b2 = new Ball(); b2 = b1; b1 100 addr value registers main memory (64- bit machine) Object References q Allow client to manipulate an object as a single entity. q Essentially a machine address (pointer) Ball b1 = new Ball(); Ball b2 = new Ball(); b2 = b1; b1 100 addr value 0.55 registers main memory (64- bit machine) 12

13 Object References q Allow client to manipulate an object as a single entity. q Essentially a machine address (pointer). Ball b1 = new Ball(); Ball b2 = new Ball(); b2 = b1; b1 100 addr value registers main memory (64- bit machine) Object References q Allow client to manipulate an object as a single entity. q Essentially a machine address (pointer). Ball b1 = new Ball(); Ball b2 = new Ball(); b2 = b1; b1 100 b2 addr value registers main memory (64- bit machine) 13

14 Object References q Allow client to manipulate an object as a single entity. q Essentially a machine address (pointer). Ball b1 = new Ball(); Ball b2 = new Ball(); b2 = b1; b1 100 b2 107 addr value registers main memory (64- bit machine) Object References q Allow client to manipulate an object as a single entity. q Essentially a machine address (pointer). Ball b1 = new Ball(); Ball b2 = new Ball(); b2 = b1; Data stored in for bit recycler (garbage collection). b1 100 b2 100 addr value registers main memory (64- bit machine) 14

15 Object References q Allow client to manipulate an object as a single entity. q Essentially a machine address (pointer). Ball b1 = new Ball(); Ball b2 = new Ball(); b2 = b1; Moving b2 also moves b1 since they are aliases that reference the same object. b1 100 b2 100 addr 100 value registers main memory (64- bit machine) Creating Many Objects q Each object is a data type value. Use new to invoke constructor and create each one. public class BouncingBalls { public static void main(string[] args) { int N = Integer.parseInt(args[0]); Ball balls[] = new Ball[N]; for (int i = 0; i < N; i++) balls[i] = new Ball(); create and ini=alize N objects while(true) { StdDraw.clear(); for (int i = 0; i < N; i++) { balls[i].move(); balls[i].draw(); StdDraw.show(20); anima=on loop 15

16 Example 4: Continuous Line Graph What is a base class to allow drawing of continuous line graphs? 31 Example: Turtle We define a Tutle class to keep track of drawing turtle (cursor) Design questions: State: what field(s) do we need to represent the state of a drawing turtle? x,y, current position angle: the current drawing direction Operations: what are some common behaviors/operations on a Turle to allow flexible drawing? A Turtle constructor, to set up the object A goforward( stepsize) method a turnleft( angle ) method 32 16

17 Turtle Graphics public class Turtle { double x, y; // turtle is at (x, y) double angle; // facing this direction public Turtle(double x0, double y0, double a0) { x = x0; y = y0; angle = a0; public void turnleft(double delta) { angle += delta; public void goforward(double d) { double oldx = x; double oldy = y; x += d * Math.cos(Math.toRadians(angle)); y += d * Math.sin(Math.toRadians(angle)); StdDraw.line(oldx, oldy, x, y); 33 N-gon What is the angle of each turn? angle = 360/ N What is the initial degree? angle /

18 N-gon public class Ngon { public static void main(string[] args) { int N = Integer.parseInt(args[0]); double angle = / N; Turtle turtle = new Turtle(0.5, 0, angle/2.0); double step = Math.sin(Math.toRadians(angle/2.0)); for (int i = 0; i < N; i++) { turtle.goforward(step); turtle.turnleft(angle); Spira Mirabilis public class Spiral { public static void main(string[] args) { int N = Integer.parseInt(args[0]); double decay = Double.parseDouble(args[1]); double angle = / N; double step = Math.sin(Math.toRadians(angle/2.0)); Turtle turtle = new Turtle(0.5, 0, angle/2.0); for (int i = 0; i < 10 * N; i++) { step /= decay; turtle.goforward(step); turtle.turnleft(angle); 36 18

19 Spira Mirabilis public class Spiral { public static void main(string[] args) { int N = Integer.parseInt(args[0]); double decay = Double.parseDouble(args[1]); double angle = / N; double step = Math.sin(Math.toRadians(angle/2.0)); Turtle turtle = new Turtle(0.5, 0, angle/2.0); for (int i = 0; i < 10 * N; i++) { step /= decay; turtle.goforward(step); turtle.turnleft(angle); Spira Mirabilis in Nature 38 19

20 Caution René Magritte. "This is not a pipe." Java. This is not a Turtle. Turle myturtle = new Turtle(0.5, 0, 45); myturle.turnleft( 90 ); OOP. Natural vehicle for studying abstract models of the real world. Example 5: A Complex Class A complex number (a + bi) is a quintessential mathematical abstraction (a + bi) + (c + di) = a + c + (b + d)i (a + bi) x (c + di) = ac - bd + (ad + bc)i a = 3 + 4i, b = i a + b = 1 + 7i a b = i a = 5 Many applications of complex numbers Fractals. Impedance in RLC circuits. Signal processing and Fourier analysis. Control theory and Laplace transforms. Quantum mechanics and Hilbert spaces

21 Argos Antennas 41 A Complex Class Design questions: State: what field(s) do we need to represent the state of a complex number? re, a number representing the real part im, a number representing the imaginary part Behaviors: what are some common behaviors of a complex number? a Complex constructor, to set up the object A abs method, to return the magnitude a tostring method, to return a string description of a complex number Mathematical operations such as +, -, * a plus method to add current complex number with another complex number a times method to multiply current complex number with another complex number 42 21

22 The Complex Class: Design Question public class Complex { double re; double im; public Complex(double real, double imag) { re = real; im = imag; public?? plus(complex b) { - What is the return type of plus? - Should plus change the state of the number 43 The Consistency (Familiarity) Design Principle Suppose a, b, and c are standard numbers (Complex numbers are numbers after all) Does a + b (think a.+(b) ) change a? no What is the return of a + b (think a.+(b)? The value of a + b so that we can write a + b + c State (no)change and return type of plus public Complex plus(complex b) { double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); 44 22

23 Complex.java public class Complex { double re; double im; instance variables public Complex(double real, double imag) { re = real; im = imag; constructor public String tostring() { return re + " + " + im + "i"; public double abs() { return Math.sqrt(re*re + im*im); public Complex plus(complex b) { double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); refers to b's instance variable creates a Complex object, and returns a reference to it public Complex times(complex b) { double real = re * b.re im * b.im; double imag = re * b.im + im * b.re; return new Complex(real, imag); methods 45 Immutability: Advantages and Disadvantages Immutable data type. Object's state does not change once constructed. Complex is an example of Immutable objects. String defined by Java is another example. Advantages. Avoid aliasing bugs. Makes program easier to debug. Limits scope of code that can change values. Pass objects around without worrying about modification. Disadvantage. New object must be created for every value. 23

24 A Simple Client public static void main(string[] args) { Complex a = new Complex( 3.0, 4.0); Complex b = new Complex(-2.0, 3.0); Complex c = a.times(b); System.out.println("a = " + a.tostring() ); System.out.println("b = " + b.tostring() ); System.out.println("c = " + c.tostring() ); % java TestClient a = i b = i c = i 47 24

26/3/ Creating Data Types. Data Type. Defining Data Types in Java. Point Charge Data Type. Charge Data Type: A Simple Client

26/3/ Creating Data Types. Data Type. Defining Data Types in Java. Point Charge Data Type. Charge Data Type: A Simple Client Data Types 3.2 Creating Data Types Data type. Set of values and operations on those values. Basic types. Data Type boolean int String Set of Values true, false -2 31 to 2 31-1 sequence of Unicode characters

More information

3.2 Creating Data Types

3.2 Creating Data Types 1 3.2 Creating Data Types Data Types Data type. Set of values and operations on those values. Basic types. Data Type boolean int String Set of Values true, false -2 31 to 2 31-1 sequence of Unicode characters

More information

3.2 Creating Data Types

3.2 Creating Data Types Data Types 3.2 Creating Data Types Data type. Set of values and operations on those values. Basic types. Data Type boolean int String Set of Values true, false -2 31 to 2 31-1 sequence of Unicode characters

More information

10. Creating Data Types

10. Creating Data Types COMPUTER SCIENCE S E D G E W I C K / W A Y N E 10. Creating Data Types Section 3.2 http://introcs.cs.princeton.edu COMPUTER SCIENCE S E D G E W I C K / W A Y N E 10. Creating Data Types Overview Point

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Admin. CS 112 Introduction to Programming. Recap: OOP. Math.random() Design. Static Math.random() method vs Random Objects

Admin. CS 112 Introduction to Programming. Recap: OOP. Math.random() Design. Static Math.random() method vs Random Objects Admin CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email:

More information

10. Creating Data Types

10. Creating Data Types Overview Point charges Turtle graphics Complex numbers Section 3.2 Object-oriented programming (OOP) Implementing a data type Object-oriented programming (OOP). To create a data type, you need provide

More information

Computer Science. 9. Creating Data Types. Computer Science COMPUTER SCIENCE. Section 3.2.

Computer Science. 9. Creating Data Types. Computer Science COMPUTER SCIENCE. Section 3.2. COMPUTER SCIENCE S E D G E W I C K / W A Y N E PA R T I : P R O G R A M M I N G I N J AVA Computer Science Computer Science An Interdisciplinary Approach Section 3.2 ROBERT SEDGEWICK K E V I N WAY N E

More information

Admin. CS 112 Introduction to Programming. Exercise: Gene Finding. Language Organizing Structure. Gene Finding. Foundational Programming Concepts

Admin. CS 112 Introduction to Programming. Exercise: Gene Finding. Language Organizing Structure. Gene Finding. Foundational Programming Concepts Admin CS 112 Introduction to Programming q PS6 (Sukoku) questions? q Planning of remaining of the semester User-Defined Data Types Yang (Richard) Yang Computer Science Department Yale University 308A Watson,

More information

3.1 Objects 7/29/2014 1:49:50 PM

3.1 Objects 7/29/2014 1:49:50 PM 3.1 Objects Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 22 21 7/29/214 1:49:5 PM A Foundation for Programming any program you might want

More information

A Foundation for Programming

A Foundation for Programming 3.1 Objects Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 7/28/2015 3:46:55 PM A Foundation for Programming any program you might

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming (Spring 2012) Lecture #31: Software Reuse through Inheritance Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading: 8.2-8.3 Recall: Instance methods instance method (or object method): Exists inside each object of a class

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 8 Lecture 18: Classes and Objects reading: 8.1-8.2 (Slides adapted from Stuart Reges, Hélène Martin, and Marty Stepp) 2 File output reading: 6.4-6.5 3 Output to files PrintStream:

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 2 Introduction to Programming Design Good Classes: Encapsulation and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

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

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

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 2 Introduction to Programming Design Good Classes: Encapsulation and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Lecture 12: Classes II

Lecture 12: Classes II Lecture 12: Classes II Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Encapsulation Encapsulation encapsulation: Hiding

More information

CLASSES AND OBJECTS. Fundamentals of Computer Science I

CLASSES AND OBJECTS. Fundamentals of Computer Science I CLASSES AND OBJECTS Fundamentals of Computer Science I Outline Primitive types Creating your own data types Classes Objects Instance variables Instance methods Constructors Arrays of objects A Foundation

More information

Lecture 11: Intro to Classes

Lecture 11: Intro to Classes Lecture 11: Intro to Classes Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Classes and objects class: A program entity

More information

A Founda4on for Programming

A Founda4on for Programming 3.1 Objects LOGO STYLE GUIDE Schools within the University Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 3/16/14 11:29 PM A Founda4on

More information

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types Classes and objects A foundation for programming any program you might want to write objects functions and modules build even bigger programs and reuse code http://www.flickr.com/photos/vermegrigio/5923415248/

More information

Procedural programming. [verb-oriented] Tell the computer to do this. (Spring 2012)

Procedural programming. [verb-oriented] Tell the computer to do this. (Spring 2012) 2/26/12 Object Oriented Programming CS 112 Introduction to Programming Procedural programming. [verb-oriented] Tell the computer to do this. (Spring 2012) Lecture #21: Designing Data Types Tell the computer

More information

Topic 27 classes and objects, state and behavior

Topic 27 classes and objects, state and behavior Topic 27 classes and objects, state and behavior "A 'class' is where we teach an 'object' to behave." -Rich Pattis Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

More information

Anatomy of a Class Encapsulation Anatomy of a Method

Anatomy of a Class Encapsulation Anatomy of a Method Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and

More information

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation Outline Problem: Create, read in and print out four sets of student grades Setting up the problem Breaking

More information

AP Computer Science. Classes and Objects

AP Computer Science. Classes and Objects AP Computer Science Classes and Objects A programming problem Given a file of cities' (x, y) coordinates, which begins with the number of cities: 6 50 20 90 60 10 72 74 98 5 136 150 91 Write a program

More information

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 4: Writing Classes Objects An object has: Presentation slides for state - descriptive characteristics Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus,

More information

Building Java Programs Chapter 8

Building Java Programs Chapter 8 Building Java Programs Chapter 8 Classes Copyright (c) Pearson 2013. All rights reserved. A programming problem Given a file of cities' (x, y) coordinates, which begins with the number of cities: 6 50

More information

A programming problem. Building Java Programs Chapter 8. Observations. A bad solution. Classes

A programming problem. Building Java Programs Chapter 8. Observations. A bad solution. Classes A programming problem Building Java Programs Chapter 8 Classes Copyright (c) Pearson 2013. All rights reserved. Given a file of cities' (x, y) coordinates, which begins with the number of cities: 6 50

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 8 Lecture 8-1: Classes and Objects reading: 8.1-8.2 2 File output reading: 6.4-6.5 3 Output to files PrintStream: An object in the java.io package that lets you print output

More information

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

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

More information

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I Object-Oriented Programming (OOP) Basics CSCI 161 Introduction to Programming I Overview Chapter 8 in the textbook Building Java Programs, by Reges & Stepp. Review of OOP History and Terms Discussion of

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 8 Lecture 8-3: Encapsulation; Homework 8 (Critters) reading: 8.3-8.4 Encapsulation reading: 8.4 2 Encapsulation encapsulation: Hiding implementation details from clients.

More information

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

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

More information

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Fall CS 101: Test 2 Name UVA  ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17. Grading Page 1 / 4 Page3 / 20 Page 4 / 13 Page 5 / 10 Page 6 / 26 Page 7 / 17 Page 8 / 10 Total / 100 1. (4 points) What is your course section? CS 101 CS 101E Pledged Page 1 of 8 Pledged The following

More information

Package. A package is a set of related classes Syntax to put a class into a package: Two rules: Example:

Package. A package is a set of related classes Syntax to put a class into a package: Two rules: Example: Packages Package A package is a set of related classes Syntax to put a class into a package: package ; public class { } Two rules: q q A package declaration must always come

More information

INHERITANCE AND OBJECTS. Fundamentals of Computer Science I

INHERITANCE AND OBJECTS. Fundamentals of Computer Science I INHERITANCE AND OBJECTS Fundamentals of Computer Science I Outline Inheritance Sharing code between related classes Putting similar objects in the same bucket Extremely common in modern OOP languages Managing

More information

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Last Class CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

More information

Classes and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates

Classes and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates Classes and objects Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates Fundamentals of Computer Science Keith Vertanen Copyright 2013 A founda4on for programming any program you might want to

More information

Implementing Classes (P1 2006/2007)

Implementing Classes (P1 2006/2007) Implementing Classes (P1 2006/2007) Fernando Brito e Abreu (fba@di.fct.unl.pt) Universidade Nova de Lisboa (http://www.unl.pt) QUASAR Research Group (http://ctp.di.fct.unl.pt/quasar) Chapter Goals To become

More information

Implementing Classes

Implementing Classes Implementing Classes Advanced Programming ICOM 4015 Lecture 3 Reading: Java Concepts Chapter 3 Fall 2006 Slides adapted from Java Concepts companion slides 1 Chapter Goals To become familiar with the process

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Basic Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

writing classes objectives chapter

writing classes objectives chapter 4 chapter objectives Define classes that serve as blueprints for new objects, composed of variables and methods. Explain the advantages of encapsulation and the use of Java modifiers to accomplish it.

More information

Admin. CS 112 Introduction to Programming. Recap: Encapsulating Data. Ask, Don't Touch. Recap: Encapsulating Data. Recap: Encapsulation/How

Admin. CS 112 Introduction to Programming. Recap: Encapsulating Data. Ask, Don't Touch. Recap: Encapsulating Data. Recap: Encapsulation/How Adin CS Introduction to Prograing q Updated class schedule Design Good Classes: Encapsulation and OOP Analysis Yang (Richard) Yang Coputer Science Departent Yale University 308A Watson, Phone: 43-6400

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

Inheritance and objects

Inheritance and objects Inheritance and objects CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014 Inheritance Overview Sharing code between related classes Putting similar objects in the same bucket

More information

Chapter 11: Creating Classes

Chapter 11: Creating Classes Chapter 11: Creating Classes Objectives Students should Recall the meaning of classes and objects in Java Know the components in the definition of a Java class Understand how constructors work Be able

More information

APCS++ Object-oriented programming

APCS++ Object-oriented programming APCS++ Object-oriented programming http://www.math-cs.gordon.edu/courses/cps323/lisp/lisp.html Passive data Active data Abstraction abstraction: A distancing between ideas and details. We can use objects

More information

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Animation (sleep and double buffering); Methods with Return; Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Animation (sleep and double buffering); Methods with Return; Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes CSEN401 Computer Programming Lab Topics: Introduction and Motivation Recap: Objects and Classes Prof. Dr. Slim Abdennadher 16.2.2014 c S. Abdennadher 1 Course Structure Lectures Presentation of topics

More information

References and objects

References and objects References and objects Arrays and objects use reference semantics. Why? efficiency. Copying large objects slows down a program. sharing. It's useful to share an object's data among methods. DrawingPanel

More information

This exam is open book. Each question is worth 3 points.

This exam is open book. Each question is worth 3 points. This exam is open book. Each question is worth 3 points. Page 1 / 15 Page 2 / 15 Page 3 / 12 Page 4 / 18 Page 5 / 15 Page 6 / 9 Page 7 / 12 Page 8 / 6 Total / 100 (maximum is 102) 1. Are you in CS101 or

More information

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes: Designing Classes part 2 CSC 1051 Data Structures and Algorithms I Getting to know classes so far Predefined classes from the Java API. Defining classes of our own: Driver classes: Account Transactions

More information

Inheritance and objects

Inheritance and objects Inheritance and objects CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2013 Inheritance Overview Sharing code between related classes Pu8ng similar objects in the same bucket Extremely

More information

Designing data types. Fundamentals of Computer Science I

Designing data types. Fundamentals of Computer Science I Designing data types Fundamentals of Computer Science I 2 Overview Object Oriented Programming (OOP) Data encapsulation Important consideration when designing a class Access modifiers Getters and setters

More information

Designing Classes part 2

Designing Classes part 2 Designing Classes part 2 CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Getting

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 12 Thomas Wies New York University Review Last lecture Modules Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic

More information

CLASSES AND OBJECTS. Fundamentals of Computer Science I

CLASSES AND OBJECTS. Fundamentals of Computer Science I CLASSES AND OBJECTS Fundamentals of Computer Science I Outline Primitive types Creating your own data types Classes Objects Instance variables Instance methods Constructors Arrays of objects A Foundation

More information

Operations. I Forgot 9/4/2016 COMPUTER SCIENCE DEPARTMENT PICNIC. If you forgot your IClicker, or your batteries fail during the exam

Operations. I Forgot 9/4/2016 COMPUTER SCIENCE DEPARTMENT PICNIC. If you forgot your IClicker, or your batteries fail during the exam COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Encapsulation. Mason Vail Boise State University Computer Science

Encapsulation. Mason Vail Boise State University Computer Science Encapsulation Mason Vail Boise State University Computer Science Pillars of Object-Oriented Programming Encapsulation Inheritance Polymorphism Abstraction (sometimes) Object Identity Data (variables) make

More information

CS 170, Section /3/2009 CS170, Section 000, Fall

CS 170, Section /3/2009 CS170, Section 000, Fall Lecture 18: Objects CS 170, Section 000 3 November 2009 11/3/2009 CS170, Section 000, Fall 2009 1 Lecture Plan Homework 5 : questions, comments? Managing g g Data: objects to make your life easier ArrayList:

More information

Defining Classes. The basic syntax for defining a class in Java is: class <class-name> [<data-declarations>] [<class-constructors>] [<methods>]

Defining Classes. The basic syntax for defining a class in Java is: class <class-name> [<data-declarations>] [<class-constructors>] [<methods>] Defining Classes As well as using predefined library classes in Java programs, it is usual to define new classes as well. The library classes model commonly occurring situations, the new classes are used

More information

Chapter 5: Writing Classes and Enums

Chapter 5: Writing Classes and Enums Chapter 5: Writing Classes and Enums CS 121 Department of Computer Science College of Engineering Boise State University August 22, 2016 Chapter 5: Writing Classes and Enums CS 121 1 / 48 Chapter 5 Topics

More information

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality Designing data types Overview Object Oriented Programming (OOP) Data encapsulation Important consideration when designing a class Access modifiers Immutability, preventing change to a variable Checking

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

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin q Issues on PS3 NumberCoolness:

More information

2.4 Input and Output. Input and Output. Standard Output. Standard Output Abstraction. Input devices. Output devices. Our approach.

2.4 Input and Output. Input and Output. Standard Output. Standard Output Abstraction. Input devices. Output devices. Our approach. Input and Output 2.4 Input and Output Input devices. Keyboard Mouse Storage Network Digital camera Microphone Output devices. Display Speakers Storage Network Printer MP3 Player Today's goal: process huge

More information

Classes and Methods: Classes

Classes and Methods: Classes Class declaration Syntax: [] Classes and Methods: Classes [] class [] [] [] When

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin q Issues on PS3 NumberCoolness:

More information

COS 226 Algorithms and Data Structures Week 3: Comparators, & Sorting (Video 5.D & Algorithms 2.1 and 2.2)

COS 226 Algorithms and Data Structures Week 3: Comparators, & Sorting (Video 5.D & Algorithms 2.1 and 2.2) COS 226 Algorithms & Data Structures p. 1/6 COS 226 Algorithms and Data Structures Week 3: Comparators, & Sorting (Video 5.D & Algorithms 2.1 and 2.2) Version: September 28, 2017 Exercise 1 Comparables

More information

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

1. Which of the following is the correct expression of character 4? a. 4 b. 4 c. '\0004' d. '4' Practice questions: 1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4' 2. Will System.out.println((char)4) display 4? a. Yes b. No 3. The expression "Java

More information

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

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

More information

CSE 143 Lecture 3. More ArrayList; object-oriented programming. reading: 10.1;

CSE 143 Lecture 3. More ArrayList; object-oriented programming. reading: 10.1; CSE 143 Lecture 3 More ArrayList; object-oriented programming reading: 10.1; 8.1-8.7 slides created by Marty Stepp http://www.cs.washington.edu/143/ Out-of-bounds Legal indexes are between 0 and the list's

More information

Packages & Random and Math Classes

Packages & Random and Math Classes Packages & Random and Math Classes Quick review of last lecture September 6, 2006 ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev Objects Classes An object

More information

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques 1 CPSC2620 Advanced Programming Spring 2003 Instructor: Dr. Shahadat Hossain 2 Today s Agenda Administrative Matters Course Information Introduction to Programming Techniques 3 Course Assessment Lectures:

More information

Imperative Languages!

Imperative Languages! Imperative Languages! Java is an imperative object-oriented language. What is the difference in the organisation of a program in a procedural and an objectoriented language? 30 class BankAccount { private

More information

CIS 110: Introduction to Computer Programming

CIS 110: Introduction to Computer Programming CIS 110: Introduction to Computer Programming Lecture 22 and 23 Objects, objects, objects ( 8.1-8.4) 11/28/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Object-oriented programming. What is

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 22 March 14, 2018 Static Methods, Java Arrays Chapters 20 & 21 Announcements HW6: Java Programming (Pennstagram) Due: Tuesday the 20 th at 11:59pm

More information

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth Outline CIS 110: Introduction to Computer Programming Lecture 22 and 23 Objects, objects, objects ( 8.1-8.4) Object-oriented programming. What is an object? Classes as blueprints for objects. Encapsulation

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

Objects and Classes -- Introduction

Objects and Classes -- Introduction Objects and Classes -- Introduction Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes

More information

CONDITIONAL EXECUTION

CONDITIONAL EXECUTION CONDITIONAL EXECUTION yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I Outline Conditional Execution if then if then Nested if then statements Comparisons

More information

CSCI 135 Final Fall Problem Points Score Total 100

CSCI 135 Final Fall Problem Points Score Total 100 CSCI 135 Final Fall 2011 Name: This exams consists of 11 problems on the following 14 pages. You may use your two- sided hand- written 8 ½ x 11 note sheet during the exam. No calculators, computers, or

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Java Primitive Data Types; Arithmetic Expressions Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example Admin CS 112 Introduction to Programming q Programming assignment 2 to be posted tonight Java Primitive Data Types; Arithmetic Expressions Yang (Richard) Yang Computer Science Department Yale University

More information

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013 CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 7 problems on the following 6 pages. You may use your single- side hand- written 8 ½ x 11 note sheet during the

More information

2.2 Input and Output. Input and Output. Digital Michelangelo Project. Terminal. Input devices. Output devices.

2.2 Input and Output. Input and Output. Digital Michelangelo Project. Terminal. Input devices. Output devices. Input and Output 2.2 Input and Output Input devices. Keyboard Mouse Hard drive Network Digital camera Speakers Hard drive Network Printer Microphone Output devices. Display MP3 Player Our approach. Define

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

1st Semester MTCE 601A COMPUTER SYSTEM SOFTWARE

1st Semester MTCE 601A COMPUTER SYSTEM SOFTWARE 1st Semester MTCE 601A COMPUTER SYSTEM SOFTWARE LECTURE-1 Syllabus Introduction 1.1 Introduction to Object Oriented 1.2 Introduction to UML 1.3 Software Process and OOA&D 1.4 Component and CBSD 1.5 Patterns

More information

CS 101 Fall 2006 Midterm 3 Name: ID:

CS 101 Fall 2006 Midterm 3 Name:  ID: You only need to write your name and e-mail ID on the first page. This exam is CLOSED text book, closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts, so be sure

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Domain-Driven Design Activity

Domain-Driven Design Activity Domain-Driven Design Activity SWEN-261 Introduction to Software Engineering Department of Software Engineering Rochester Institute of Technology Entities and Value Objects are special types of objects

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

CS 1302 Chapter 9 (Review) Object & Classes

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

More information