1 / 25

Building Java Programs

Building Java Programs. Chapter 8: Classes Lecture 8-2: Constructors, Encapsulation, Critters reading: 8.4 - 8.6. Announcements. HW7 due TOMORROW at 11:30 HW8 is going out TODAY, due NEXT WEDNESDAY Everyone is getting 1 extra late day to use as you see fit

kedma
Download Presentation

Building Java Programs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Building Java Programs Chapter 8: Classes Lecture 8-2: Constructors, Encapsulation, Critters reading: 8.4 - 8.6

  2. Announcements • HW7 due TOMORROW at 11:30 • HW8 is going out TODAY, due NEXT WEDNESDAY • Everyone is getting 1 extra late day to use as you see fit • Final is NEXT FRIDAY in lecture

  3. Review: Instance method public class Point { int x; int y; // Changes the location of this Point object. public void translate(int dx, int dy) { x += dx; y += dy; } } • The translate method no longer has a Point p parameter. • How does the method know which point to move?

  4. The implicit parameter • implicit parameter:The object on which an instance method is called. • During the call p1.translate(11, 6); , the object referred to by p1 is the implicit parameter. • During the call p2.translate(1, 7); , the object referred to by p2 is the implicit parameter. • The instance method can refer to that object's fields. • We say that it executes in the context of a particular object. • translate can refer to the x and y of the object it was called on.

  5. Object initialization: constructors reading: 8.4 self-check: #10-12 exercises: #9, 11, 14, 16

  6. Initializing objects • Currently it takes 3 lines to create a Point and initialize it: Point p = new Point(); p.x = 3; p.y = 8; // tedious • We'd rather pass the fields' initial values as parameters: Point p = new Point(3, 8); // better! • We are able to this with most types of objects in Java.

  7. Constructors • constructor: Initializes the state of new objects. public type(parameter(s)) { statement(s) ; } • runs only when the client uses the new keyword • does not specify a return type;it implicitly returns the new object being created • If a class has no constructor, Java gives it a default constructor with no parameters that sets all fields to 0.

  8. Constructor example public class Point { int x; int y; // Constructs a Point at the given x/y location. public Point(int initialX, int initialY) { x = initialX; y = initialY; } public void translate(int dx, int dy) { x = x + dx; y = y + dy; } }

  9. Tracing a constructor call • What happens when the following call is made? Point p1 = new Point(7, 2); public Point(int initialX, int initialY) { x = initialX; y = initialY; } public void translate(int dx, int dy) { x = x + dx; y = y + dy; }

  10. Client code, version 3 public class PointMain3 { public static void main(String[] args) { // create two Point objects Point p1 = new Point(5, 2); Point p2 = new Point(4, 3); // print each point System.out.println("p1: (" + p1.x + ", " + p1.y + ")"); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); // move p2 and then print it again p2.translate(2, 4); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); } } OUTPUT: p1: (5, 2) p2: (4, 3) p2: (6, 7)

  11. The toString method reading: 8.6 self-check: #18, 20-21 exercises: #9, 14

  12. Printing objects • By default, Java doesn't know how to print objects: Point p = new Point(10, 7); System.out.println("p: " + p); // p is Point@9e8c34 • We can print a better string (but this is cumbersome): System.out.println("p: (" + p.x + ", " + p.y + ")"); • We'd like to be able to print the object itself: // desired behavior System.out.println("p: " + p); // p is (10, 7)

  13. The toString method • tells Java how to convert an object into a String • called when an object is printed/concatenated to a String: Point p1 = new Point(7, 2); System.out.println("p1 is " + p1); • If you prefer, you can write .toString() explicitly. System.out.println("p1 is " + p1.toString()); • Every class has a toString, even if it isn't in your code. • The default is the class's name and a hex (base-16) number: Point@9e8c34

  14. toString syntax public String toString() { code that returns a String ; } • Example: // Returns a String representing this Point. public String toString() { return "(" + x + ", " + y + ")"; } • The method name, return, parameters must match exactly. • Modify our client code to use toString.

  15. Client code // This client program uses the Point class. public class PointMain { public static void main(String[] args) { // create two Point objects Point p1 = new Point(7, 2); Point p2 = new Point(4, 3); // print each point System.out.println("p1: " + p1); System.out.println("p2: " + p2); // compute/print each point's distance from the origin System.out.println("p1's distance from origin: " + p1.distanceFromOrigin()); System.out.println("p2's distance from origin: " + p1.distanceFromOrigin()); // move p1 and p2 and print them again p1.translate(11, 6); p2.translate(1, 7); System.out.println("p1: " + p1); System.out.println("p2: " + p2); // compute/print distance from p1 to p2 System.out.println("distance from p1 to p2: " + p1.distance(p2)); } }

  16. Encapsulation reading: 8.5 - 8.6 self-check: #13-17 exercises: #5

  17. Battle to the Death • Write a program that simulates a battle to the death • Each player has a 50% chance of attacking the other • Battle ends when either player’s isAlive() returns false • Each player should be an instantiation of the Hero class: public class Hero { int hitPoints; // life meter public Hero() { hitPoints = 100; } public int getAttack() { return 10; } public boolean isAlive() { return hitPoints > 0; } public String toString() { return "HP: " + hitPoints; } }

  18. Solution code import java.util.*; public class BattleZone { public static void main(String[] args) { Random rand = new Random(); // to decide attacker Hero victoria = new Hero(); Hero caio = new Hero(); // end when !victoria.isAlive() || !caio.isAlive() while (victoria.isAlive() && caio.isAlive()) { int turn = rand.nextInt(2); if (turn == 0) { // I attack caio System.out.println("Victoria attacks!"); int damage = victoria.getAttack(); caio.hitPoints -= damage; } else { System.out.println("Caio attacks!"); int damage = caio.getAttack(); victoria.hitPoints -= damage; } System.out.println("Victoria's " + victoria); System.out.println("Caio's " + caio); System.out.println(); } ...

  19. Solution code, con’t. ... if (victoria.isAlive()) { System.out.println("Victoria wins!"); } else { System.out.println("Caio wins!"); } } }

  20. A Critical Bug • But what happens if you add this to the program? Random rand = new Random(); Hero victoria = new Hero(); Hero caio = new Hero(); // catastrophe! caio.hitPoints = 1000000; victoria.hitPoints = -5234; Output (always): Caio wins! • It is bad style to write objects in a way that gives direct access to fields

  21. Encapsulation • encapsulation: Hiding implementation details of an object from its clients. • Encapsulation provides abstraction. • separates external view (behavior) from internal view (state)

  22. Homework 8:Critters

  23. Critters • A simulation world with animal objects with behavior: • getMove movement • eat eating food • fight animal fighting • toString letter to display • getColor color to display • You must implement: • Bear • Lion • Tiger • Husky

  24. 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. • Your animal must keep state (as fields) so that it can make a single move, and know what moves to make later.

  25. Critter exercise • Write a critter class Cougar (the dumbest of all animals): • eat: Always eats. • fight: Always pounces. • getColor: Blue if the Cougar has never fought; red if he has. • getMove: The drunk Cougar staggers left 2, right 2, repeats. • toString: Always returns "C".

More Related