Lecture 11: More on Classes

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 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-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:
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.
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.
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.
Copyright 2010 by Pearson Education Homework 9: Critters (cont.) reading: HW9 spec.
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
Building Java Programs
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
Homework 8: Critters (cont.)
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.
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.
Homework 8: Critters (cont.)
Building Java Programs
Building Java Programs
Homework 9: Critters (cont.)
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
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:

Lecture 11: More on Classes Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved.

Object Initialization: Constructors

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.

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. However, if a class has at least one constructor(with or without parameters), this default constructor is overridden by the new constructor(s).

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

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

Client code public class PointMain { 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); } OUTPUT: p1: (5, 2) p2: (4, 3) p2: (6, 7)

Multiple constructors A class can have multiple constructors. Each one must accept a unique set of parameters. Exercise: Write an additional 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; }

example public class Point { int x; int y; // Constructs a Point at the origin. public Point(){ x=0; y=0; } // 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; ... example

Client code public class PointMain { public static void main(String[] args) { // create two Point objects Point p1 = new Point(5, 2); Point p2 = new Point(); // 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: (0, 0) p2: (2, 4)

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

Constructors If a class has no constructor, Java gives it a default constructor with no parameters that sets all integer fields to 0, booleans to false, Strings to empty, etc... However, if a class has at least one constructor(with or without parameters), this default constructor is overridden by the new constructor(s).

Default constructor public class Point { int x; int y; //no constructors } public class PointMain { public static void main(String[] args) { Point p2 = new Point(); // ok, uses default constr Point p1 = new Point(5, 2); //error, no such constr

Overriding Default Constructors public class Point { int x; int y; //override default constructor public Point(int newX, int newY){ x=newX; y=newY; } public class PointMain { public static void main(String[] args) { Point p2 = new Point(4,-2); // ok Point p1 = new Point(); //error, no default constr.

Lab Modify both the Point and Circle class to each include at least two constructors. At least one of the constructors should include enough parameters to initialize all of the fields. In the driver class, create some Points and Circles by using different constructors.

Encapsulation

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 // accessor methods // 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; } // accessor methods 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);

Client code public class PointMain { 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.getX()+”,”+p1.getY()+")"); System.out.println("p2:(“+p2.getX()+”,”+p2.getY()+")"); } OUTPUT: p1:(5,2) p2:(4,3)

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.

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

Fixing shadowing Inside setLocation, 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

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

Static methods/fields

Static members instance: Part of an object, rather than shared by the class. 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 field1 double field2 behavior: public void method3() public int method4() public void method5() object #2 object #3

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.

Final Static fields Final static field: public static final type name; or, public static final type name = value; Example: public static final int NUMOFMONTHS = 12; Final static field: A class constant whose value cannot be changed. Usually public. ALL CAPS by convention.

Modules in Java libraries // Java's built in Math class is a module public class Math { public static final double PI = 3.14159265358979323846; ... public static int abs(int a) { if (a >= 0) { return a; } else { return -a; } public static double toDegrees(double radians) { return radians * 180 / PI; You can even open the code for Math.java in the Java src.zip install file in the JDK folder.

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

Examples public class PointMain { public static void main(String[] args) { int a=Math.abs(-4); //abs is static String b=“hello”; int b=b.length(); //length() is instance Scanner console=new Scanner(System.in); console.nextInt(); //nextInt is instance }

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

Static methods static method: Stored in a class, not in an object. // 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.

Math has only static methods // Java's built in Math class is a module public class Math { public static final double PI = 3.14159265358979323846; ... public static int abs(int a) { if (a >= 0) { return a; } else { return -a; } public static double toDegrees(double radians) { return radians * 180 / PI; You can even open the code for Math.java in the Java src.zip install file in the JDK folder.

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;

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

tells Java how to convert an object into a String 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 name @ object's memory address (base 16) Point@9e8c34

toString syntax toString can be overwritten to return a desired String representation of the object. 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. return "(" + x + ", " + y + ")";

Point class // accessor methods // 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; } // accessor methods public int getX() { return x; public int getY() { return y; public String toString() { return "(" + x + ", " + y + ")"; public void setLocation(int newX, int newY) { x = newX; y = newY; public void translate(int dx, int dy) { setLocation(x + dx, y + dy);

Client code public class PointMain { public static void main(String[] args) { Point p1 = new Point(5, 2); Point p2 = new Point(4, 3); System.out.println("p1: ” + p1); //same as above System.out.println(”p2: ” + p2.toString()); } OUTPUT: p1:(5,2) p2:(4,3)

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, does not usually declare any static fields (except final) an object class : Defines a new type of objects. example: Point, BankAccount, Date, Car, TetrisPiece 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

Lab 2 Write the Student class with the following 5 data fields: name, address, ID, gpa, String mathClass and the following methods: printStudentInfo(): Prints all of the student data fields, each on its own line. updateGPA(double newgpa): Update GPA. String graduationStatus(): gpa<1, “not graduating”. gpa>=1, “graduating”. String toString(): String representation of Student. For example, returns full name and ID. Write client/driver class to test Student class.

Lab 2 Student should have FOUR constructors. A default constructor which initializes name to “John Doe”, address to an empty string, ID to 0, gpa to 0.0 and mathClass to an empty string. A constructor which accepts two parameters: one for the name and one for the ID. All other parameters are set to an empty string or 0. A constructor which accepts one parameter for the name. All other parameters are set to an empty string or 0. A constructor which accepts parameters for all of the fields.

Lab 3 Write a class called MyComplex which models the complex numbers a+bi. It contains: Two private double variables real and img. A default constructor to create a complex number at 0+0i. A constructor which takes two double a and b and initializes this complex number to a+bi. Setters and Getters(accessors and mutators) for private variables real and img. toString() that returns “(a+bi”) form of the complex number. isReal() and isImaginary() that returns whether this complex number is real or imaginary, respectively. For example, 4 is real while 5i is imaginary but 4+5i is neither and 0 is both.

Lab 3 6) void add(MyComplex c): Add complex number c to this complex number. Hint: (a+bi)+(c+di)=(a+c)+(b+d)i 7) void multiply(MyComplex c): Multiply c to this complex number. Hint: (a+bi)*(c+di)=(ac-bd)+(ad+bc)i 8) void conjugate() changes this complex number into its conjugate. Hint: The conjugate of a+bi is a-bi.

Lab 3 9) double argument() returns the argument(angle) in radians of this complex number. This angle is the same as theta of polar coordinates. Hint: Use Math.atan2(y,x). 10) double magnitude() returns the magnitude or length of this complex number. Hint: The magnitude of a+bi is Math.sqrt(a*a+b*b). For example, the magnitude of 3+4i is 5.

Lab 3 MyComplex should also contains the following static methods: 1)MyComplex addNew(MyComplex a, MyComplex b) returns a complex number that is the sum of a and b. 2)MyComplex multiplyNew(MyComplex a, MyComplex b) returns the complex number that is the product a*b.

Lab 3 Write a driver class ComplexTester to test all of the methods/constructors of MyComplex.