Building Java Programs

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 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Methods and Constructors reading: self-checks: #1-12.
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 8 Lecture 8-1: Classes and Objects reading: self-checks: #1-9 exercises: #1-4.
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:
Packages. Package A package is a set of related classes Syntax to put a class into a package: package ; public class { …} Two rules:  A package declaration.
Based on slides at buildingjavaprograms.com Objects and Classes, take 2 Managing Complexity with Programmer-Defined Types  Classes are programmer-defined.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Constructors and Encapsulation reading: self-checks: #10-17.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, this reading: self-checks: #13-17 exercises:
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-1: Classes and Objects reading: self-checks: #1-9 exercises: #1-4.
Building Java Programs Chapter 8 Classes Copyright (c) Pearson All rights reserved.
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.
Building Java Programs Chapter 8 Lecture 8-1: Classes and Objects; Fields and Methods reading: 8.1 – 8.2.
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 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Topic 27 classes and objects, state and behavior Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Methods and Constructors reading: self-checks: #1-12.
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:
Object Oriented Programming
Building Java Programs
Lecture 11: More on Classes
Building Java Programs Chapter 8
Building Java Programs Chapter 8
Classes and Objects, State and Behavior
Lecture 8-3: Encapsulation, this
Building Java Programs
Object initialization: constructors
Topic 28 classes and objects, part 2
Building Java Programs
Topic 29 classes and objects, part 3
Building Java Programs
Building Java Programs
Classes and objects Readings: 8.1.
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.
References and objects
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Kinds of methods accessor: A method that lets clients examine object state. Examples: distance, distanceFromOrigin often has a non-void return type mutator: A.
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Building Java Programs
Building Java Programs
Special instance methods: toString
Building Java Programs
Building Java Programs
Classes and objects Readings: 8.1.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 8-2: Object Behavior (Methods) and Constructors
Building Java Programs
Building Java Programs Chapter 8
Building Java Programs
Building Java Programs
Chapter 11 Inheritance and Encapsulation and Polymorphism
Topic 29 classes and objects, part 3
Building Java Programs
Building Java Programs
Topic 29 classes and objects, part 3
Presentation transcript:

Building Java Programs Chapter 8 Lecture 8-2: More Objects: null, toString, Constructors, this, Encapsulation reading: 8.2 – 8.4

The null reference reading: 8.3

The null reference null : A value that does not refer to any object. The elements of an array of objects are initialized to null. String[] words = new String[5]; DrawingPanel[] windows = new DrawingPanel[3]; index 1 2 3 4 value null words index 1 2 value null windows

Things you can do w/ null store null in a variable or an array element String s = null; words[2] = null; print a null reference System.out.println(s); // null ask whether a variable or array element is null if (words[2] == null) { ... pass null as a parameter to a method System.out.println(null); // null return null from a method (often to indicate failure) return null;

Null pointer exception dereference: To access data or methods of an object with the dot notation, such as s.length() . It is illegal to dereference null (causes an exception). null is not an object, so it has no methods or data. String[] words = new String[5]; words[0] = "hello"; words[2] = "goodbye"; // words[1], [3], [4] are null for (int i = 0; i < words.length; i++) { System.out.println("word is: " + words[i]); words[i] = words[i].toUpperCase(); // ERROR } Output: word is: hello word is: null Exception in thread "main" java.lang.NullPointerException index 1 2 3 4 value "HELLO" null "goodbye"

Looking before you leap You can check for null before calling an object's methods. String[] words = new String[5]; words[0] = "hello"; words[2] = "goodbye"; // words[1], [3], [4] are null for (int i = 0; i < words.length; i++) { if (words[i] != null) { words[i] = words[i].toUpperCase(); } index 1 2 3 4 value "HELLO" null "GOODBYE" words

Two-phase initialization 1) initialize the array itself (each element is initially null) 2) initialize each element of the array to be a new object String[] words = new String[4]; // phase 1 for (int i = 0; i < words.length; i++) { coords[i] = "word" + i; // phase 2 } index 1 2 3 value "word0" "word1" "word2" "word3" words

The toString method reading: 8.2

Any redundancies? public class PointMain { public static void main(String[] args) { // create two Point objects Point p1 = new Point(); p1.x = 5; p1.y = 2; Point p2 = new Point(); p2.x = 4; p2.x = 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); } OUTPUT: p1: (5, 2) p2: (4, 3) p2: (6, 7)

Printing objects By default, Java doesn't know how to print objects: Point p = new Point(); p.x = 10; p.y = 7; System.out.println("p is " + p); // p is Point@9e8c34 // better, but cumbersome; p is (10, 7) System.out.println("p is (" + p.x + ", " + p.y + ")"); // desired behavior System.out.println("p is " + p); // p is (10, 7)

The toString method A method that tells Java how to convert an object into a string Implicitly called when you use an object in a String context: Point p1 = new Point(7, 2); System.out.println("p1: " + p1); The above code is really doing the following: System.out.println("p1: " + p1.toString()); Every class has a toString, even if you don’t define one. Default: class's name @ object's memory address Point@9e8c34

toString syntax public String toString() { <code that returns a String representation>; } Method header must match exactly. Example: // Returns a String representing this Point return "(" + x + ", " + y + ")";

Quarantine client, v3 public class Quarantine3 { ... public static void quarantineCities(Graphics g, Point3[] cities, Point3 quarPoint, int quarRad) { g.setColor(Color.RED); System.out.println("Quarantined cities: "); g.drawOval(quarPoint.x - quarRad, quarPoint.y - quarRad, 2 * quarRad, 2 * quarRad); for (int i = 0; i < cities.length; i++) { if (quarPoint.distance(cities[i]) <= quarRad) { cities[i].draw(g); System.out.println("\t" + cities[i]); } } } }

Object initialization: constructors reading: 8.3

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 specify the fields' initial values at the start: Point p = new Point(3, 8); // better! We are able to do this with most types of objects in Java.

Constructors constructor: Initializes the state of new objects. public <type>(<parameters>) { <statement(s)>; } runs when the client uses the new keyword How does this differ from previous methods? no return type is specified; it implicitly "returns" the new object being created This is not the same as having a void return type!! If a class has no constructor, Java gives it a default constructor with no parameters that sets all fields to 0 (or equivalent).

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; ...

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 += dx; y += dy; x 7 y 2 x y p1

Common constructor bugs 1. Re-declaring fields as local variables ("shadowing"): public Point(int initialX, int initialY) { int x = initialX; int y = initialY; } This declares local variables with the same name as the fields, rather than storing values into the fields. The fields remain 0. 2. Giving parameters the same name as fields: public Point(int x, int y) { x = x; y = y; This is another form of shadowing. We’ll see how to fix this soon.

Common constructor bugs 3. Accidentally giving the constructor a return type: public void Point(int initialX, int initialY) { x = initialX; y = initialY; } This is actually not a constructor, but a method named Point

Multiple constructors A class can have multiple constructors. Each one must accept a unique set of parameters. Exercise: Write a Point constructor with no parameters that initializes the point to (0, 0). // Constructs a new point at (0, 0). public Point() { x = 0; y = 0; }

Quarantine client, v4 public class Quarantine4 { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("cities.txt")); Scanner console = new Scanner(System.in); // read in city locations int cityCount = input.nextInt(); Point4[] cities = new Point4[cityCount]; for (int i = 0; i < cityCount; i++) { cities[i] = new Point4(input.nextInt(), input.nextInt()); } ... // get quarantine location/radius System.out.print("Quarantine site x and y? "); Point4 quarPoint = new Point4(console.nextInt(), console.nextInt()); ... }

The keyword this reading: 8.3

The implicit parameter implicit parameter: The object on which an instance method is called. During the call p1.draw(g); the object referred to by p1 is the implicit parameter. During the call p2.draw(g); 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. draw can refer to the x and y of the object it was called on.

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: this.<field> Call a method: this.<method>(<parameters>); One constructor this(<parameters>); can call another:

Variable shadowing shadowing: 2 variables with same name in same scope. Normally illegal, except when one variable is a field. public class Point { int x; 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.

Fixing shadowing Inside setLocation, public class Point { int x; 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

Calling another constructor public class Point { int x; 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

Encapsulation reading: 8.4

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

A field that cannot be accessed from outside the class 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); ^

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);

Point class // A Point object represents an (x, y) location. public class Point5 { private int x; private int y; // Constructs a Point at the given x/y location. public Point5(int x, int y) { this.x = x; this.y = y; } // Constructs a Point at the origin. public Point5() { this(0, 0); } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public int getX() { return x; } public int getY() { return y; } ...

Point class ... // Draw this Point. public void draw(Graphics g) { g.fillOval(x, y, 3, 3); g.drawString(toString(), x, y); } // Changes the location of this Point object. public void setLocation(int x, int y) { setX(x); setY(y); } // Shift this Point the given amounts. public void translate(int dx, int dy) { setLocation(x + dx, y + dy); } // Calculate the distance between this Point and another one. public double distance(Point5 other) { int dx = x - other.getX(); int dy = y - other.getY(); return Math.sqrt(dx * dx + dy * dy); } // Print a string representation of this Point public String toString() { return "(" + x + ", " + y + ")"; } }

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.