CSCI 1103: Object-Oriented Objects

Similar documents
CSCI 1103: Simple Objects

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CS 302 Week 9. Jim Williams

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Chapter 4 Defining Classes I

Java Review. Fundamentals of Computer Science

Object Oriented Programming in C#

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

APCS Semester #1 Final Exam Practice Problems

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

Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007

Chapter 11: Create Your Own Objects

CS 1302 Chapter 9 (Review) Object & Classes

Java for Non Majors Spring 2018

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

CSCI 2041: Basic OCaml Syntax and Features

CS 231 Data Structures and Algorithms, Fall 2016

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

CS 101 Fall 2006 Midterm 3 Name: ID:

Object Oriented Programming

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

PIC 20A The Basics of Java

Project 1. Java Control Structures 1/17/2014. Project 1 and Java Intro. Project 1 (2) To familiarize with

CS 211: Existing Classes in the Java Library

CSCI 1103: Introduction

Classes Classes 2 / 36

BM214E Object Oriented Programming Lecture 8

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

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

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

Anatomy of a Class Encapsulation Anatomy of a Method

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

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

CSCI 1103: File I/O, Scanner, PrintWriter

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

Java Object Oriented Design. CSC207 Fall 2014

Media Computation. Lecture 15.2, December 3, 2008 Steve Harrison

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

CS111: PROGRAMMING LANGUAGE II

Classes Classes 2 / 35

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Introduction to Programming Using Java (98-388)

QUIZ. What is wrong with this code that uses default arguments?

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

CH. 2 OBJECT-ORIENTED PROGRAMMING

Chapter 4: Writing Classes

CHAPTER 7 OBJECTS AND CLASSES

Simple Java Reference

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Class 9: Static Methods and Data Members

Ch 7 Designing Java Classes & Class structure. Fields have data values define/describe an instance

Introduction to Java Applications

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

Principles of Object Oriented Programming. Lecture 4

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

CSCI 1103: File I/O, Scanner, PrintWriter

CS 211: Methods, Memory, Equality

Comments are almost like C++

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Introduction to Java

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

CS 1331 Exam 1 ANSWER KEY

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

CSCI 161 Introduction to Computer Science

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

CS112 Lecture: Working with Numbers

ECE 122. Engineering Problem Solving with Java

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Creating an object Instance variables

Instance Method Development Demo

Robots. Byron Weber Becker. chapter 6

Object Oriented Programming

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

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

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

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

CS558 Programming Languages

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CS1083 Week 2: Arrays, ArrayList

CHAPTER 7 OBJECTS AND CLASSES

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

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Final Exam CS 152, Computer Programming Fundamentals December 5, 2014

COMP 202 Java in one week

Chapter 15: Object Oriented Programming

Lecture 5: Methods CS2301

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

CSCI 1301: Introduction to Computing and Programming Spring 2019 Lab 10 Classes and Methods

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

CS11 Java. Fall Lecture 1

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Transcription:

CSCI 1103: Object-Oriented Objects Chris Kauffman Last Updated: Fri Nov 10 10:41:24 CST 2017 1

Logistics Reading from Eck Ch 5 on Objects/Classes Goals Finish arrays of objects Static fields Non-static methods Lab08: Simple object definitions Stock object Methods in same java file Project Spec up Due a week from Wed 2

Static/Non-static Stuff so far The keyword static in Java roughly translates to "belongs to the whole class and all objects" So far we have written the following static methods public class MyClass{ public static int dosomething(...){... Non-static fields public class Thing{ int part1; double part2; String part3; Nothing special about them, invoked with MyClass.doSomethig(..) Must pass in all parameters to the methods Each Thing has its own part1, part2, part3 4 Things means 12 pieces of data, 4 ints, 4 doubles, 4 String references 3

Static Class Fields A static field indicates there is only 1 memory location for the entire class, NOT one per object Closest thing Java has to a global variable Seen examples of static fields from some classes double pie = Math.PI; double natbase = Math.E; PrintStream ps = System.out; Syntax static establish a static field is simple public class Mixed{ public static int e; public String f; Every instance of a Mixed has its own f // static field // non-static field There is only one integer e, accessible via Mixed.e 4

Demo of Static vs Non-Static Fields 1 class OnlyStatic{ 2 public static int a; // both static 3 public static String b; 4 5 class OnlyNon{ 6 public int c; // both non-static 7 public String d; 8 9 class Mixed{ 10 public static int e; // one static 11 public String f; // one non-static 12 13 14 public class StaticFields{ 15 public static void main(string args[]){ 16 OnlyStatic.a = 5; OnlyStatic.b = "bb"; 17 18 // OnlyNon.c = 4; // ERROR: non-static field 19 // OnlyNon.d = "ddd"; // ERROR: non-static field 20 OnlyNon x = new OnlyNon(); 21 x.c = 10; x.d = "dd"; 22 OnlyNon y = new OnlyNon(); 23 y.c = 15; y.d = "dddd"; 24 25 Mixed.e = 20; 26 // Mixed.f = "ff"; // ERROR: non-static field 27 28 Mixed z = new Mixed(); 29 z.f = "ff"; 30 Mixed w = new Mixed(); 31 w.f = "ffff"; 32 33 5

Exercise: Recap what we learned about static fields 1. What s the difference between a static and a non-static field? 2. How many of each kind of field are gotten when calling new 3. Draw a quick diagram of the following. public class Thing{ public int red; public double blue; public static int green; public static void main(string args[]){ Thing x = new Thing(); Thing y = new Thing(); x.red = 5; y.blue = 7.0; ///////// DRAW HERE //////////// // which works / doesn t? Thing.green = 9; Thing.red = 10; 6

Non-static Methods static roughly means class-level, as in belonging to the entire class Non static roughly means instance-level, as in associated with a specific instance/object Non-static methods are ALWAYS invoked with a specific object/instance String s = "hello"; String t = "goodbye"; int len1 = s.length(); // 5 int len2 = t.length(); // 7 During a the execution of a non-static method, the keyword this refers to the object on which the method is running 7

Compare: Static vs Non-static Method Defs/Calls Static 1 public class Omelet{ 2 int eggs; 3 int cheese; 4 double cookedfor; 5 String extras; 6 7 static void cookfor(omelet om, 8 double time){ 9 om.cookedfor += time; 10 11 static void addegg(omelet om){ 12 om.eggs++; 13 14 15 main(){ 16 Omelet standard = new Omelet(); 17 int x = 5; 18 Omelet.addEgg(standard); 19 Omelet.cookFor(standard, 2.5); 20 Non-static 1 public class OOOmelet{ 2 int eggs; 3 int cheese; 4 double cookedfor; 5 String extras; 6 7 void cookfor(double time){ 8 this.cookedfor += time; 9 10 11 void addegg(){ 12 this.eggs++; 13 14 15 main(){ 16 OOOmelet standard = new OOOmelet(); 17 int x = 5; 18 standard.addegg(); 19 standard.cookfor(2.5); 20 Examine OOOmelet.java to see full implementation 8

this variable: reference to current object Variable this is automatically created in non-static methods Gets filled in with the value of the object being operated on standard.addegg(); ^^^^^^^^ during addegg(), this will refer to OOOmelet standard coronary.addegg() ^^^^^^^^ during addegg(), this will refer to OOOmelet coronary 9

Constructors Objects usually have necessary fields initialized at creation Special method called a constrctor Method name is always identical to class name, return type is omitted CK commonly uses this.field = param; to initialize fields public class OOOmelet{... // Constructor to initialize fields to given values. cookedfor is // always initialized to 0.0. public OOOmelet(int eggs, int cheese, String extras){ this.eggs = eggs; // set field eggs to parameter eggs this.cheese = cheese; // set field cheese to parameter cheese this.extras = extras; // set field extras to parameter extras this.cookedfor = 0.0; // always set cookedfor to 0.0... public class OOOmeletMain{ public static void main(string args[]){ OOOmelet small = new OOOmelet(2,5,"ham"); // smallish OOOmelet OOOmelet large = new OOOmelet(5,8,"bacon"); // largeish OOOmelet... 10

Exercise: Draw a Memory Diagram Show the OOOMeletMain.java and OOOMelet.java.exercise Running the main() method, trace execution Draw memory diagrams of what things look like at the numbered locations Note: May hit some locations more than once Important: Don t forget the automatic this variable in non-static methods 11

Easy Printing: tostring() method Most complex objects provide a tostring() method to produce nice output Compare OOOmelet small = new OOOmelet(2,5,"ham"); System.out.println(small); NO tostring() method: OOOmelet@2a139a55 WITH tostring() method: 3 eggs, 5 oz cheese, cooked for 1.5 mins, extras: ham public class OOOmelet{ private int eggs; private int cheese; private double cookedfor; private String extras; // Create a pretty string version of the OOOmelet. public String tostring(){ return String.format("%d eggs, %d oz cheese, cooked for %.1f mins, extras: %s", this.eggs, this.cheese, this.cookedfor, this.extras); 12

String.format() for tostring() Extremely useful method static method of String class Works like printf() but instead of printing to the screen, creates a string and returns it Example: String s = String.format("apples: %d weight: %.1f kind: %s", 5, 1.27, "Honeycrisp"); System.out.println(s); // apples: 5 weight: 1.3 kind: Honeycrisp Often used in tostring() methods to format info on object for display Also used in testing files to produce error messages containing data for debugging 13

Exercise: Dog Constructor and tostring() Define constructor for Dog class to the right Infer arguments/defaults from use in main() Define tostring() method Infer format from use in main() Make use of String.format() public class Dog{ public String name; public int age; public boolean hasbone; // CONSTRUCTOR // tostring() public static void main(string args[]){ Dog s = new Dog("Stout",3); Dog r = new Dog("Rufus",1); r.hasbone = true; System.out.println(s.toString()); System.out.println(r.toString()); > javac Dog.java > java Dog Name: Stout Age: 3 Bone? false Name: Rufus Age: 1 Bone? true 14

Access Modifiers Access Levels for Fields/Methods by other stuff Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N Mostly concerned with public and private, read about others on your own Most projects will specify required public methods, maybe public fields Most of the time you are free to create additional private methods and fields to accomplish your task Official docs on access modifiers http://docs.oracle.com/javase/tutorial/java/javaoo/accesscontrol.html 15

Accessor, Mutator, Class Invariant Common Java convention is to make all fields private private fields are only visible within on.java file accessor and mutator methods provided to work with object data Accessor often referred to as "getter" as in geteggs() Mutator sometimes called a "setters" but often have other names, intended to change object data Important: changing object data preserves any invariants of the class: related fields public class OOOmelet{ public int eggs; public int cheese; // Retrieve number of eggs public int geteggs(){ return this.eggs; // Add an egg to the omelet // if cooking hasn t begun public void addegg(){ if(this.cookedfor > 0){ System.out.println("Yuck"); else{ this.eggs++; 16

Invariants in Classes OOOmelets (In-class) Once cooking starts, cannot add eggs Can only add time to cooking, not subtract Extra ingredients must be specified up front Linear Equations (Lab09) y = m x + b Left and right sides of equation are always equal Changing x updates y, vice versa Portfolio (Proj4) Adding a stock increases the stockcount Buying stocks deducts from cash Selling stocks adds to cash Cannot withdraw() more cash than is available Cannot sell more shares than available 17

Why Getters vs. Public Fields Simple objects can probably have public fields, direct access Don t do this as you ll be penalized on manual inspection Slightly more complex objects like OOOmelet might get away with public fields but would allow.. "Uncooking" of omelets: o.cookedfor = 0.0; Add eggs after being cooked Using private fields prevents this Complex objects like Printstream from System.out must preserve invariants: different parts must agree with each other. Changing one field might screw up another one Deny direct access via private fields Mutation methods like println() keep all fields synchronized Abstraction Up and Down Break a problem into smaller parts. Define public methods between those parts. Think about internal details for one part at a time. Recurse for subparts as needed. 18

private Fields / public methods OOOmelet.java UseOOOmelet.java public class OOOmelet{ private int eggs; private int cheese; private double cookedfor; private String extras; public double geteggs(){ return this.eggs; public double getcooktime(){ return this.cookedfor; public void addegg(){...... Must access fields through public methods public class UseOOOmelet{ public static void main(string args[]){ OOOmelet om = new OOOmelet(2,4,"ham"); // CORRECT: public methods int eggs = om.geteggs(); om.addegg(); // INCORRECT: No such symbol om.eggs = 5; // compile error // CORRECT: public method om.cookefor(1.0); // INCORRECT: No such symbol om.cookedfor=0.0; // compile error 19

private Fields Visible only in One Java File private means visible in current Java File only Within OOOmelet.java, the name eggs is visible for all OOOmelets Even if that name is associated with "some other" OOOmelet See moreeggs() method: accessing that.eggs despite it being a private variable boolean moreeggs = small.moreeggsthan(large) // OOOmelet.java public class OOOmelet{ private int eggs; // Return true if this omelet has more // eggs than the parameter omelet public boolean moreeggsthan(ooomelet that){ if(this.eggs > that.eggs){ // OK!!! return true; else{ return false; // OOOmeletMain.java public class OOOmeletMain{ public static void main(string args[]){ OOOmelet small = new OOOmelet(2,5,"ham"); OOOmelet large = new OOOmelet(5,8,"bacon"); 20

Name Binding Resolution Mechanics Java follows rules to determine where names are defined: name binding Resolution matters for bare names: no class/object association om.eggs = 5; // specific object s field this.cookedfor = 5; // specific object s field int c = om.getcalories(); // specific object s method this.addegg); // specific object s method Omelet.egg_cals = 123; // specific class (static) cookedfor = 1.23; // BARE NAME for field addegg(); // BARE NAME for method To determine where name var binds look at 1. Local variables 2. Parameters to method 3. Fields of class 4. Potentially outside class (won t do this in CS 1103) 21

Exercise: Binding Resolution NUMBERS declare a name LETTERS are bare name references Match LETTERS to NUMBERS to match bare name to where it is defined To determine where name var binds look at 1. Local variables 2. Parameters to method 3. Fields of class 1 public class OOOmelet{ 2 private int eggs; // 1 3 private int cheese; // 2 4 private double cookedfor; // 3 5 private String extras; // 4 6 7 public int geteggs(){ // 5 8 return eggs; //// A 9 10 11 public void cookfor(double time){ 12 double cookedfor = // 6 13 this.cookedfor; //// B 14 cookedfor += time; //// C 15 16 17 public void addcheese(int cheese){ // 7 18 cheese += cheese; 19 //// D and E 20 21 22 public boolean foodpoisoningiminent(){ 23 return cookedfor < (1.0 * geteggs()); 24 //// F G 25 26 22

Answers: Binding Resolution Let Num Note A 1 field eggs B 2 field cookedfor C 6 local cookedfor D 7 param cheese E 7 param cheese F 3 field cookedfor G 5 this.geteggs() 1 public class OOOmelet{ 2 private int eggs; // 1 3 private int cheese; // 2 4 private double cookedfor; // 3 5 private String extras; // 4 6 7 public int geteggs(){ // 5 8 return eggs; //// A 9 10 11 public void cookfor(double time){ 12 double cookedfor = // 6 13 this.cookedfor; //// B 14 cookedfor += time; //// C 15 16 17 public void addcheese(int cheese){ // 7 18 cheese += cheese; 19 //// D and E 20 21 22 public boolean foodpoisoningiminent(){ 23 return cookedfor < (1.0 * geteggs()); 24 //// F G 25 23

Exercise: Gotchya s with Constructor Name Binding Common to initialize fields in constructors Determine what s wrong with these constructors Give a correct constructor public class OOOmelet{ public int eggs; public int cheese; public double cookedfor; public String extras; // BAD CONSTRUCTOR 1 public OOOmelet(int eggs, int cheese, String extras) { eggs = eggs; cheese = cheese; extras = extras; cookedfor = 0.0; public class OOOmelet{ public int eggs; public int cheese; public double cookedfor; public String extras; // BAD CONSTRUCTOR 2 public OOOmelet(int eg, int ch, String ex) { int eggs = eg; int cheese = ch; String extras = ex; double cookedfor = 0.0; 24

Answer: Gotchya s with Constructor Name Binding The names of parameters like eggs or local variable int eggs can shadow fields Fields never get modified as shadows receive assignments Use this.name = name; or change names of parameters public class OOOmelet{ public int eggs; public int cheese; public double cookedfor; public String extras; // CORRECT CONSTRUCTOR 1 // Use this.field to specify // field initialization public OOOmelet(int eggs, int cheese, String extras) { this.eggs = eggs; this.cheese = cheese; this.extras = extras; this.cookedfor = 0.0; public class OOOmelet{ public int eggs; public int cheese; public double cookedfor; public String extras; // CORRECT CONSTRUCTOR 2 // Vary names of parameters to // avoid conflicts public OOOmelet(int eg, int ch, String ex) { eggs = eg; cheese = ch; extras = ex; cookedfor = 0.0; 25

Multiple Methods: Overloading In Java, several methods can share the same name SO LONG as each has a distinct a number and/or type of arguments Called overloading a method public class OOOmelet{ // Constructor to initialize fields to // given values. cookedfor is always // initialized to 0.0. public OOOmelet(int eggs, int cheese, String extras) { this.eggs = eggs; this.cheese = cheese; this.extras = extras; this.cookedfor = 0.0; // Constructor to initialize fields to // given values. extras is blank and // cookedfor is 0.0. public OOOmelet(int eggs, int cheese) { this.eggs = eggs; this.cheese = cheese; this.extras = ""; this.cookedfor = 0.0; // Add an egg to the omelet public void addegg(){ if(this.cookedfor > 0){ System.out.println("Yuck"); else{ this.eggs++; // Add multiple eggs to the omelet public void addegg(int neggs){ for(int i=0; i<neggs; i++){ addegg(); public static void main(string args[]){ OOOmelet oma = new OOOMelet(3,2,"ham"); OOOmelet omb = new OOOMelet(4,6); oma.addegg(2); omb.addegg(); 26

Exercise: Review Questions on Object-Oriented Objects 1. Describe the difference between a static field and a non-static field. How many of each exit when a class is used? 2. The class Foo has a static method called double bar(int x, String s). Describe how to invoke/call this method. 3. What is a constructor? How are they named? Give an example of how they are called. 4. The class Flurbo has a non-static method named int schmeckle(double z). Describe how to invoke/call it. 5. In what context can the keyword this be used? Where can it not be used? 6. What does the keyword this refer to? Can it ever be null? 7. What order does the Java compiler search for bindings of bare variable names to variable declarations? 8. Why would one choose to make fields of a class private? 9. What are accessor methods? What are mutator methods? 27