Building Java Programs

Similar documents
CS 112 Introduction to Programming

Assignment 11: Critters

Building Java Programs

Lecture 12: Classes II

CSc 110, Spring 2017 Lecture 38: Critters. Adapted from slides by Marty Stepp and Stuart Reges

CS 112 Introduction to Programming. (Spring 2012)

CSc 110, Spring 2017 Lecture 37: Critters. Adapted from slides by Marty Stepp and Stuart Reges

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Admin. Admin. Recap. Recap: Polymorphism and Arrays. the Google doc to record the teaming

CSE 142, Autumn 2018 Programming Assignment #9: Critters (20 points) Due Tuesday, December 4th, 9:00 PM

Critters. Critter #2 Attack.ROAR Attack.POUNCE Attack.SCRATCH. Critter #1

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

Critter #1 Attack.ROAR random winner #2 wins #1 wins Attack.POUNCE #1 wins random winner #2 wins Attack.SCRATCH #2 wins #1 wins random winner

Building Java Programs

Building Java Programs

Building Java Programs Chapter 8

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

Homework 9: Critters (cont.)

Building Java Programs

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

Lecture 11: Intro to Classes

Admin. CS 112 Introduction to Programming. Recap: The Critter Class. Recap: Event-Driven Programming. State Machine Driven Cougar.

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs

BBM 102 Introduc0on to Programming II Spring 2014

CSE 142 SPRING 2008 FINAL EXAM

CIS 110: Introduction to Computer Programming

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

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

CS 312 Final Fall 2013

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

Classes as Blueprints: How to Define New Types of Objects

CSE 143X: Accelerated Computer Programming I/II HW5: Critters (due Friday, October 30, :30pm)

Programming Languages and Techniques (CIS120)

Slide 1 CS 170 Java Programming 1

CSE115 Introduction to Computer Science I Coding Exercise #7 Retrospective Fall 2017

Chapter 6 Introduction to Defining Classes

Java Classes & Primitive Types

Programming Languages and Techniques (CIS120)

Constants are named in ALL_CAPS, using upper case letters and underscores in their names.

Chapter 4 Defining Classes I

CSE 142, Spring 2010 Final Exam Wednesday, June 9, Name: Student ID #: Rules:

ITI Introduction to Computing II

Object-Oriented Programming (Java)

More Java Basics. class Vector { Object[] myarray;... //insert x in the array void insert(object x) {...} Then we can use Vector to hold any objects.

CSE 373. Objects in Collections: Object; equals; compareto; mutability. slides created by Marty Stepp

CS1004: Intro to CS in Java, Spring 2005

CS 312 Final Fall Your Name SOLUTION SOLUTION SOLUTION SOLUTION SOLUTION. Your UTEID SOLUTION SOLUTION SOLUTION SOLUTION SOLUTION _

ITI Introduction to Computing II

Object Oriented Programming. Week 1 Part 3 Writing Java with Eclipse and JUnit

Inheritance and Polymorphism. CS180 Fall 2007

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CSE 142 Sample Final Exam #1

Instance Members and Static Members

PIC 10A. Lecture 15: User Defined Classes

The Nervous Shapes Example

Greenfoot! Introducing Java With Games And Simulations. Workshop material. Wombats. Object Orientation. Asteroids, Ants and other creatures.

Programming Abstractions

Building Java Programs

An introduction to Java II

CIS 110 Introduction To Computer Programming. December 19th, 2011 Final. Answer key

Java Classes & Primitive Types

CS170 Introduction to Computer Science Midterm 2

Name: CSC143 Exam 1 1 CSC 143. Exam 1. Write also your name in the appropriate box of the scantron

CSE 142, Winter 2007 Final Exam. Name:

CS 162 Intro to CS II. Structs vs. Classes

CS 312 Final Fall 2016

Programming Languages and Techniques (CIS120)

CSE 142 Sample Final Exam #1 (based on Spring 2005's final; thanks to Stuart Reges)

Programming Languages and Techniques (CIS120)

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Programming Languages and Techniques (CIS120)

Example: Count of Points

Example: Fibonacci Numbers

Java Review. Fundamentals of Computer Science

CS 170 Java Programming 1. Week 13: Classes, Testing, Debugging

Objects and Classes (1)

Object-Oriented Programming Concepts

CS/ENGRD 2110 FALL2017. Lecture 4: The class hierarchy; static components

ASSIGNMENT 4 Classes and Objects

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

CS/ENGRD 2110 FALL Lecture 4: The class hierarchy; static components

CSE142 Sample Final Exam Key Autumn 2018

Topic 27 classes and objects, state and behavior

The return Statement

Industrial Programming

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Assignment 2 - Specifications and Modeling

CS 11 C++ track: lecture 1

3.1 Class Declaration

Programming Exercise

ICS 4U. Introduction to Programming in Java. Chapter 10 Notes

Creating Java Programs with Greenfoot

CSE 143 Au04 Midterm 1 Page 1 of 9

Instructions. Objectives:

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

CSE142 Final Exam Key Summer 2018

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

Transcription:

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. Encapsulation forces abstraction. separates external view (behavior) from internal view (state) protects the integrity of an object's data 3 Private fields A field that cannot be accessed from outside the class private type name; Examples: private int id; private String name; Client code won't compile if it accesses private fields: PointMain.java:11: x has private access in Point System.out.println(p1.x); ^ 4

Accessing private state // A "read-only" access to the x field ("accessor") public int getx() { return x; // Allows clients to change the x field ("mutator") public void setx(int newx) { x = newx; Client code will look more like this: System.out.println(p1.getX()); p1.setx(14); 5 Point class, version 4 // A Point object represents an (x, y) location. public class Point { private int x; private int y; public Point(int initialx, int initialy) { x = initialx; y = initialy; public int getx() { return x; public int gety() { return y; public double distancefromorigin() { return Math.sqrt(x * x + y * y); public void setlocation(int newx, int newy) { x = newx; y = newy; public void translate(int dx, int dy) { setlocation(x + dx, y + dy); 6

Benefits of encapsulation Abstraction between object and clients Protects object from unwanted access Example: Can't fraudulently increase an Account's balance. Can change the class implementation later Example: Point could be rewritten in polar coordinates (r, θ) with the same methods. Can constrain objects' state (invariants) Example: Only allow Accounts with non-negative balance. Example: Only allow Dates with a month from 1-12. 7 The keyword this reading: 8.3 8

The this keyword this : Refers to the implicit parameter inside your class. (a variable that stores the object on which a method is called) Refer to a field: Call a method: One constructor can call another: this.field this.method(parameters); this(parameters); 9 Variable shadowing shadowing: 2 variables with same name in same scope. Normally illegal, except when one variable is a field. public class Point { private int x; private int y; // this is legal public void setlocation(int x, int y) { In most of the class, x and y refer to the fields. In setlocation, x and y refer to the method's parameters. 10

Fixing shadowing public class Point { private int x; private int y; public void setlocation(int x, int y) { this.x = x; this.y = y; Inside setlocation, To refer to the data field x, say this.x To refer to the parameter x, say x 11 Calling another constructor public class Point { private int x; private int y; public Point() { this(0, 0); // calls (x, y) constructor public Point(int x, int y) { this.x = x; this.y = y; Avoids redundancy between constructors Only a constructor (not a method) can call another constructor 12

Homework 8: Critters reading: HW8 assignment spec 13 Critters A simulation world with animal objects with behavior: eat eating food fight animal fighting getcolor color to display getmove movement tostring letter to display You must implement: Ant Bird Hippo Vulture Husky (creative) 14

A Critter subclass public class name extends Critter { extends Critter tells the simulator your class is a critter an example of inheritance Write some/all 5 methods to give your animals behavior. 15 How the simulator works When you press "Go", the simulator enters a loop: move each animal once (getmove), in random order if the animal has moved onto an occupied square, fight! if the animal has moved onto food, ask it if it wants to eat Key concept: The simulator is in control, NOT your animal. Example: getmove can return only one move at a time. getmove can't use loops to return a sequence of moves. It wouldn't be fair to let one animal make many moves in one turn! Your animal must keep state (as fields) so that it can make a single move, and know what moves to make later. 16

Critter exercise: Cougar Write a critter class Cougar (the dumbest of all animals): Method constructor eat fight getcolor getmove tostring public Cougar() Always eats. Always pounces. Blue if the Cougar has never fought; red if he has. Walks west until he finds food; then walks east until he finds food; then goes west and repeats. "C" Behavior 17 Ideas for state You must not only have the right state, but update that state properly when relevant actions occur. Counting is helpful: How many total moves has this animal made? How many times has it eaten? Fought? Remembering recent actions in fields is helpful: Which direction did the animal move last? How many times has it moved that way? Did the animal eat the last time it was asked? How many steps has the animal taken since last eating? How many fights has the animal been in since last eating? 18

Keeping state How can a critter move west until it finds food? public Direction getmove() { while (animal has not eaten) { return Direction.EAST; while (animal has not eaten a second time) { return Direction.EAST; private int moves; // total moves made by this Critter public Direction getmove() { moves++; if (moves % 4 == 1 moves % 4 == 2) { return Direction.WEST; else { return Direction.EAST; 19 import java.awt.*; // for Color public class Cougar extends Critter { private boolean west; private boolean fought; public Cougar() { west = true; fought = false; public boolean eat() { west =!west; return true; Cougar solution public Attack fight(string opponent) { fought = true; return Attack.POUNCE; 20

Cougar solution public Color getcolor() { if (fought) { return Color.RED; else { return Color.BLUE; public Direction getmove() { if (west) { return Direction.WEST; else { return Direction.EAST; public String tostring() { return "C"; 21 Testing critters Focus on one specific critter of one specific type Only spawn 1 of each animal, for debugging Make sure your fields update properly Use println statements to see field values Look at the behavior one step at a time Use "Tick" rather than "Go" 22

Critter exercise: Snake Method constructor eat fight getcolor getmove tostring Behavior public Snake() Never eats always forfeits black 1 E, 1 S; 2 W, 1 S; 3 E, 1 S; 4 W, 1 S; 5 E, "S" 23 Determining necessary fields Information required to decide what move to make? Direction to go in Length of current cycle Number of moves made in current cycle Remembering things you've done in the past: an int counter? a boolean flag? 24

Snake solution import java.awt.*; // for Color public class Snake extends Critter { private int length; // # steps in current horizontal cycle private int step; // # of cycle's steps already taken public Snake() { length = 1; step = 0; public Direction getmove() { step++; if (step > length) { // cycle was just completed length++; step = 0; return Direction.SOUTH; else if (length % 2 == 1) { return Direction.EAST; else { return Direction.WEST; public String tostring() { return "S"; 25