Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Constructors; Encapsulation reading: 8.3 - 8.6 self-checks: #13-18, 20-21.

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 Encapsulation, this, Subclasses.
1 Building Java Programs Chapter 8: Classes These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
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:
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:
Object Oriented Programming Concepts OOP – reasoning about a program as a set of objects rather than as a set of actions Object – a programming entity.
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.
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 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 19: encapsulation, inheritance reading: (Slides adapted from Stuart.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
CS 112 Introduction to Programming User-Defined Data Types Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
1 Object state: fields. Fields field: A variable inside an object that represents part of its internal state.  Each object will have its own copy of.
CSCI 162 Classes.
CSC 142 Computer Science II Zhen Jiang West Chester University
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.
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.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
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-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Object Oriented Programming
Building Java Programs
Lecture 11: More on Classes
CSC240 Computer Science III
Building Java Programs Chapter 8
Classes and Objects, State and Behavior
Lecture 8-3: Encapsulation, this
Building Java Programs
CSc 110, Autumn 2016 Lecture 31: Encapsulation
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.
CSE 142 Lecture Notes Defining New Types of Objects
Building Java Programs
Building Java Programs
Lecture 11: Intro to Classes
Kinds of methods accessor: A method that lets clients examine object state. Examples: distance, distanceFromOrigin often has a non-void return type mutator: A.
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Building Java Programs
Building Java Programs
Special instance methods: toString
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
reading: 8.6 self-check: #18, exercises: #9, 14
Building Java Programs
Chapter 11 Inheritance and Encapsulation and Polymorphism
Topic 29 classes and objects, part 3
Building Java Programs
Topic 29 classes and objects, part 3
Presentation transcript:

Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Constructors; Encapsulation reading: self-checks: #13-18, exercises: #5, 9, 14

Copyright 2010 by Pearson Education 2 The toString method reading: 8.6 self-check: #18, exercises: #9, 14

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

Copyright 2010 by Pearson Education 4 The toString method tells Java how to convert an object into a String Point p1 = new Point(7, 2); System.out.println("p1: " + p1); // the above code is really calling the following: System.out.println("p1: " + p1.toString()); Every class has a toString, even if it isn't in your code. Default: class's object's memory address (base 16)

Copyright 2010 by Pearson Education 5 toString syntax public String toString() { code that returns a String representing this object ; } Method name, return, and parameters must match exactly. Example: // Returns a String representing this Point. public String toString() { return "(" + x + ", " + y + ")"; }

Copyright 2010 by Pearson Education 6 Object initialization: constructors reading: 8.4 self-check: #10-12 exercises: #9, 11, 14, 16

Copyright 2010 by Pearson Education 7 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 this with most types of objects in Java.

Copyright 2010 by Pearson Education 8 Constructors constructor: Initializes the state of new objects. public type ( parameters ) { statements ; } runs when the client uses the new keyword no return type is specified; 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.

Copyright 2010 by Pearson Education 9 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; }... }

Copyright 2010 by Pearson Education 10 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 y p1

Copyright 2010 by Pearson Education 11 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)

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

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

Copyright 2010 by Pearson Education 14 Encapsulation reading: self-check: #13-17 exercises: #5

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

Copyright 2010 by Pearson Education 16 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); ^

Copyright 2010 by Pearson Education 17 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);

Copyright 2010 by Pearson Education 18 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); }

Copyright 2010 by Pearson Education 19 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 Account s with non-negative balance. Example: Only allow Date s with a month from 1-12.

Copyright 2010 by Pearson Education 20 The keyword this reading: 8.7

Copyright 2010 by Pearson Education 21 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:

Copyright 2010 by Pearson Education 22 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.

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

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