Copyright 2010 by Pearson Education Homework 9: Critters (cont.) reading: HW9 spec.

Slides:



Advertisements
Similar presentations
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Advertisements

Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else ; Cumulative sum reading: 4.1, 4.3, 4.5; "Procedural.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8: Classes Lecture 8-1: Intro to Classes and Objects reading:
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Copyright 2010 by Pearson Education 1 Assignment 11: Critters reading: HW11 assignment spec.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Introduction to Java Programming Language May 2015 Kyung Eun Park COSC Introduction to Computer Science II.
Copyright 2010 by Pearson Education 1 Assignment 11: Critters.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-x: Critters reading: HW9 Spec.
Building Java Programs Chapter 8 Classes. 2 A programming problem Given a file of cities' (x, y) coordinates, which begins with the number of cities:
Writing Classes (Chapter 4)
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Constructors and Encapsulation reading: self-checks: #10-17.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-4: Static Methods and Fields.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Building Java Programs Chapter 8 Classes Copyright (c) Pearson All rights reserved.
Copyright 2010 by Pearson Education Homework 9: Critters (cont.) reading: HW9 spec.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
Building Java Programs Chapter 8 Classes Copyright (c) Pearson All rights reserved.
Building Java Programs Chapter 8 Classes Copyright (c) Pearson All rights reserved.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ) reading:
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Building Java Programs Program Logic and Indefinite Loops.
Building Java Programs Chapter 8 Lecture 8-3: Object state; Homework 8 (Critters) reading:
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ); Discussion of Homework 9:
Week 12 - Monday.  What did we talk about last time?  Defining classes  Class practice  Lab 11.
Copyright 2010 by Pearson Education Building Java Programs Homework 8: Critters reading: Critters Assignment Spec.
Copyright 2010 by Pearson Education Homework 8: Critters reading: HW8 spec.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ); Discussion of Homework 9:
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Copyright 2009 by Pearson Education Building Java Programs Chapter 8: Classes Lecture 8-3: More Critters, static.
Copyright 2009 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Constructors; Encapsulation reading: self-checks: #13-18,
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Building Java Programs
Building Java Programs
Lecture 11: More on Classes
Homework 8: Critters reading: HW8 spec.
Building Java Programs
Building Java Programs
Building Java Programs Chapter 8
HW11 Assignment Specification
Lecture 8-3: Encapsulation, this
Critter exercise: Snake
Object initialization: constructors
Homework 8: Critters (cont.)
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 12: Classes II Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Building Java Programs
Homework 8: Critters (cont.)
Building Java Programs
Building Java Programs
Homework 9: Critters (cont.)
Building Java Programs
Building Java Programs
Chapter 9 9-3: Polymorphism reading: 9.3
Building Java Programs
Building Java Programs
Presentation transcript:

Copyright 2010 by Pearson Education Homework 9: Critters (cont.) reading: HW9 spec

Copyright 2010 by Pearson Education 2 Critter exercise: Snake MethodBehavior constructor public Snake() eat Never eats fight always forfeits getColor black getMove 1 E, 1 S; 2 W, 1 S; 3 E, 1 S; 4 W, 1 S; 5 E,... toString"S"

Copyright 2010 by Pearson Education 3 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?

Copyright 2010 by Pearson Education 4 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"; }

Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-4: Static Methods and Fields

Copyright 2010 by Pearson Education 6 Critter exercise: FratGuy All the frat guys are trying to get to the same party. The party is at a randomly-generated board location (On the 60-by-50 world) They stumble north then east until they reach the party

Copyright 2010 by Pearson Education 7 A flawed solution import java.util.*; // for Random public class FratGuy extends Critter { private int partyX; private int partyY; public FratGuy() { Random r = new Random(); partyX = r.nextInt(60); partyY = r.nextInt(50); } public Direction getMove() { if (getY() != partyY) { return Direction.NORTH; } else if (getX() != partyX) { return Direction.EAST; } else { return Direction.CENTER; } Problem: Each frat guy goes to his own party. We want all frat guys to share the same party location.

Copyright 2010 by Pearson Education 8 Static members static: Part of a class, rather than part of an object. Object classes can have static methods and fields. Not copied into each object; shared by all objects of that class. class state: private static int staticFieldA private static String staticFieldB behavior: public static void someStaticMethodC() public static void someStaticMethodD() object #1 state: int field2 double field2 behavior: public void method3() public int method4() public void method5() object #2 state: int field1 double field2 behavior: public void method3() public int method4() public void method5() object #3 state: int field1 double field2 behavior: public void method3() public int method4() public void method5()

Copyright 2010 by Pearson Education 9 Static fields private static type name ; or, private static type name = value ; Example: private static int theAnswer = 42; static field: Stored in the class instead of each object. A "shared" global field that all objects can access and modify. Like a class constant, except that its value can be changed.

Copyright 2010 by Pearson Education 10 Accessing static fields From inside the class where the field was declared: fieldName // get the value fieldName = value ; // set the value From another class (if the field is public ): ClassName. fieldName // get the value ClassName. fieldName = value ; // set the value generally static fields are not public unless they are final Exercise: Modify the BankAccount class shown previously so that each account is automatically given a unique ID. Exercise: Write the working version of FratGuy.

Copyright 2010 by Pearson Education 11 BankAccount solution public class BankAccount { // static count of how many accounts are created // (only one count shared for the whole class) private static int objectCount = 0; // fields (replicated for each object) private String name; private int id; public BankAccount() { objectCount++; // advance the id, and id = objectCount; // give number to account }... public int getID() { // return this account's id return id; }

Copyright 2010 by Pearson Education 12 FratGuy solution import java.util.*; // for Random public class FratGuy extends Critter { // static fields (shared by all frat guys) private static int partyX = -1; private static int partyY = -1; // object constructor/methods (replicated into each frat guy) public FratGuy() { if (partyX < 0 || partyY < 0) { Random r = new Random(); // the 1st frat guy created partyX = r.nextInt(60); // chooses the party location partyY = r.nextInt(50); // for all frat guys to go to } public Direction getMove() { if (getY() != partyY) { return Direction.NORTH; } else if (getX() != partyX) { return Direction.EAST; } else { return Direction.CENTER; }

Copyright 2010 by Pearson Education 13 Static methods // the same syntax you've already used for methods public static type name ( parameters ) { statements ; } static method: Stored in a class, not in an object. Shared by all objects of the class, not replicated. Does not have any implicit parameter, this ; therefore, cannot access any particular object's fields. Exercise: Make it so that clients can find out how many total BankAccount objects have ever been created.

Copyright 2010 by Pearson Education 14 BankAccount solution public class BankAccount { // static count of how many accounts are created // (only one count shared for the whole class) private static int objectCount = 0; // clients can call this to find out # accounts created public static int getNumAccounts() { return objectCount; } // fields (replicated for each object) private String name; private int id; public BankAccount() { objectCount++; // advance the id, and id = objectCount; // give number to account }... public int getID() { // return this account's id return id; }

Copyright 2010 by Pearson Education 15 Advanced FratGuy exercise A party is no fun if it's too crowded. Modify FratGuy so that a party will be attended by no more than 10 frat guys. Every 10th frat guy should choose a new party location for himself and the next 9 of his friends to be constructed. first ten frat guys go to party #1 next ten frat guys go to party #2...

Copyright 2010 by Pearson Education 16 Advanced FratGuy solution import java.util.*; // for Random public class FratGuy extends Critter { // static fields (shared by all frat guys) private static int ourPartyX = -1; private static int ourPartyY = -1; private static int objectCount = 0; // chooses the party location for future frat guys to go to public static void choosePartySpot() { Random r = new Random(); ourPartyX = r.nextInt(60); ourPartyY = r.nextInt(50); } // object fields/constructor/methods (replicated in each frat guy) private int myPartyX; private int myPartyY;...

Copyright 2010 by Pearson Education 17 Advanced FratGuy solution 2... public FratGuy() { // every 10th one chooses a new party spot for future FratGuys if (objectCount % 10 == 0) { choosePartySpot(); } // must remember his party spot so they aren't all the same myPartyX = ourPartyX; myPartyY = ourPartyY; } public Direction getMove() { if (getY() != myPartyY) { return Direction.NORTH; } else if (getX() != myPartyX) { return Direction.EAST; } else { return Direction.CENTER; }

Copyright 2010 by Pearson Education 18 Multi-class systems Most large software systems consist of many classes. One main class runs and calls methods of the others. Advantages: code reuse splits up the program logic into manageable chunks Main Class #1 main method1 method2 Class #2 method3 method5 Class #3 method4 method6

Copyright 2010 by Pearson Education 19 Redundant program 1 // This program sees whether some interesting numbers are prime. public class Primes1 { public static void main(String[] args) { int[] nums = { , , 53, 142}; for (int i = 0; i < nums.length; i++) { if (isPrime(nums[i])) { System.out.println(nums[i] + " is prime"); } // Returns the number of factors of the given integer. public static int countFactors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { count++; // i is a factor of the number } return count; } // Returns true if the given number is prime. public static boolean isPrime(int number) { return countFactors(number) == 2; }

Copyright 2010 by Pearson Education 20 Redundant program 2 // This program prints all prime numbers up to a maximum. public class Primes2 { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Max number? "); int max = console.nextInt(); for (int i = 2; i <= max; i++) { if (isPrime(i)) { System.out.print(i + " "); } } System.out.println(); } // Returns true if the given number is prime. public static boolean isPrime(int number) { return countFactors(number) == 2; } // Returns the number of factors of the given integer. public static int countFactors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { count++; // i is a factor of the number } } return count; }

Copyright 2010 by Pearson Education 21 Classes as modules module: A reusable piece of software, stored as a class. Example module classes: Math, Arrays, System // This class is a module that contains useful methods // related to factors and prime numbers. public class Factors { // Returns the number of factors of the given integer. public static int countFactors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { count++; // i is a factor of the number } return count; } // Returns true if the given number is prime. public static boolean isPrime(int number) { return countFactors(number) == 2; }

Copyright 2010 by Pearson Education 22 More about modules A module is a partial program, not a complete program. It does not have a main. You don't run it directly. Modules are meant to be utilized by other client classes. Syntax: class. method ( parameters ); Example: int factorsOf24 = Factors.countFactors(24);

Copyright 2010 by Pearson Education 23 Using a module // This program sees whether some interesting numbers are prime. public class Primes { public static void main(String[] args) { int[] nums = { , , 53, 142}; for (int i = 0; i < nums.length; i++) { if (Factors.isPrime(nums[i])) { System.out.println(nums[i] + " is prime"); } // This program prints all prime numbers up to a given maximum. public class Primes2 { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Max number? "); int max = console.nextInt(); for (int i = 2; i <= max; i++) { if (Factors.isPrime(i)) { System.out.print(i + " "); } } System.out.println(); }

Copyright 2010 by Pearson Education 24 Modules in Java libraries // Java's built in Math class is a module public class Math { public static final double PI = ;... public static int abs(int a) { if (a >= 0) { return a; } else { return -a; } public static double toDegrees(double radians) { return radians * 180 / PI; }

Copyright 2010 by Pearson Education 25 Summary of Java classes A class is used for any of the following in a large program: a program : Has a main and perhaps other static methods. example: GuessingGame, Birthday, MadLibs, CritterMain does not usually declare any static fields (except final ) an object class : Defines a new type of objects. example: Point, BankAccount, Date, Critter, FratGuy declares object fields, constructor(s), and methods might declare static fields or methods, but these are less of a focus should be encapsulated (all fields and static fields private ) a module : Utility code implemented as static methods. example: Math