From charlesreid1

Chapter 8: Classes

Sections:

8.1 Object Oriented Programming

8.2 Object state/behavior

8.3 Object initialization: constructors

8.4 Encapsulation

8.5 Case study: Stock class

Chapters 1-7 focused on procedural programming. Now, we'll dive into classes, core concept in Java.

Start with terminology - like prior chapter covering objects, lots of terminology.

Discuss abstraction and encapsulation.

Discuss ideas for design of new classes, and programs to use them.

Section 8.1: Object Oriented Programming

Definitions

Definitions:

  • Object oriented programming
  • Object
  • State
  • Behavior
  • Client
  • Driver

Material

Core concept:

  • state and behavior
  • state: values (internal data) stored by object
  • behavior: set of actions
  • Ultimately, it is all just data - numbers, strings, other objects, but methods are also like data - a set of instructions, a recipe

Driver program:

  • The program that sets things in motion (confusing because this is also an object in Java, but think of it as the non-object object
  • Objects are not program!
  • Objects are components of programs!

Encapsulation

  • Representing details
  • Taking care of details
  • Bank analogy again - bank acct object defines some data, like name and address, balance, acct no., some can be changed, some cannot

Classes:

  • Classes: template, definition, blueprint
  • Objects: actual implementation, actual instance

Class:

  • object
  • object
  • object

house blueprint

  • house
  • house
  • house

Point objects: (x,y)

  • Provided by awt
  • has methods defined
  • Usage of an object, understanding how to call its methods
  • History reference: DOS (cmd line) --> Mac (GUI)
  • Verb noun --> noun verb

Section 8.2: State and Behavior

Definitions

Definitions:

  • Mutator
  • Accessor
  • Cohesion

Material

Working through construction of Point class

Components:

  • Fields (data stored in each object)
  • Methods (behavior)
  • Constructor (init code)
  • Encapsulation (data protection)

Object state: fields

  • x and y are two Point fields
  • Separate init pair x and y for each instance (blueprint)
  • Creation of client code to create 2 points, compute distance

Object behavior: methods

  • Behavior --> instance methods
  • Translating point: example of abstraction
  • Just translate the point - we don't care how you do it!
  • Alt is pkublic static method, lots of detail exposed, not optimal
  • IF we change point class to be 3D, now we have to change the class, and change stuff that is outside the class

Implicit parameter:

  • Let's consider a method (an instance method - meaning a non-static method)
  • The method has implied knowledge of the object it operates on
  • That is, if a method is defined for an object, the method knows about that object
  • This object (itself) is called the "implicit parameter" because it doesn't need to be explicitly declared
  • Python: we have to say self.x, self.y
  • Java we say this.x, this.y, but we can also just say x, y

Methods for accessing changing data:

  • Objects, Java in general, obsessed with concept of data protection
  • Strange fixation, at beginning
  • Let's explore this.
  • Bank acct example: code needs to protect data, provide accessors to appropriate code, not unfettered access to all data
  • Healthcare record system in Java: served to large hospital network, access control REALLY important

To deal with data protections:

  • All data is private by default
  • Accessor: getParam() method
  • Mutator: setParam() method
  • Le the object change the data itself, provide a high-level method for accessing that functionality

toString() method:

  • Strings are the central object in Java
  • Concatenation works with all objects and primitive types
  • Printing objects by default prints address in memory
  • Can replace this default behavior by overriding toString() method

Section 8.3: Object Init and Constructors

Definitions

Definitions:

  • this

Material

Objects are collections of data

  • How do we initialize that data?
  • Don't always want user to initialize (e.g., initialize a new bank account with 1E16 dollars).

We initialize data using constructor

  • What constructor looks like
  • Syntax for constructors

Example of Point class:

public class Point {
  int x;
  int y;
  public Point( int x0, int y0) {
    x = x0; // or, this.x = x0;
    y = y0; // or, this.y = y0;
  }
}

Other methods:

  • distance from origin
  • to string
  • translate

Constructors:

  • Default constructor
  • Constructor with points

Common constructor syntax error:

  • Redeclaring fields (variables)
  • Using void with constructor
  • Constructors DO NOT have return type

This keyword:

  • Less confusing than using implicit parameters
  • Be explicit
Point p1 = new Point(10,5);
Point p2 = new Point(4,5);

Point 1 and point 2 are referencing particular parts of memory.

  • this.x less ambiguous
  • prevents later squashing of variable x, prevents ambiguity (argument named "x", private member named "x" - which one?)
  • Mixing LOCAL method variables, LOCAL method arguments, and CLASS WIDE variables is a no-no!

Multiple constructors:

  • Different ways to construct objects
  • That is, can have default arguments, Point() vs Point(1,1)

Section 8.4: Encapsulation

Definitions

Definitions:

  • Encapsulation
  • Abstraction
  • Class invariant

Material

Radio:

  • Example of system with many internal complexities that the user doesn't care about, components with different values
  • Partly about keeping everything simple and easy for the user - don't want the user to have to understand radio circuits
  • Partly about protecting things - the user may pick BAD values of components, and fry the radio

Private fields:

  • We can't just trust the user not to touch the things they shouldn't
  • Bank account example: need protections on data
  • This is the purpose behind get/set methods
  • If we don't protect data, users only need to know the name of the variable
  • Bank example:
public BankAcct { 
  public BankAcct(name, addr) { 
    int this.account = 1234;
    int this.balance = 0;
  }
}

With the above example, the user just needs to know the variable "balance," and they can set their balance to whatever they want. Not secure!

Syntax for private data:

private int num;
private String label = "CreativeNames";

If you lock up the class data, be nice to the users - provide them a way to access the data!

Example:

  • Encapsulated Point class and PointDriver class

Class invariants:

  • Class to represent time intervals
  • Private fields for hours/minutes
  • What if restrictions on values?
  • In constructor, pass in values of hours/minutes
  • Deal with minutes > 60 in constructor, with a percentage
  • When we add minutes - same problem (IDENTIFY A PATTERN - ENCAPSULATE THE CODE)
  • Class invariants are assertions about class state (data) that MUST be true
  • Wrap up the "add" functionality, and call an internal add() method in constructor

Printing:

  • Redefine toString() method to customize printing behavior
  • Example TimeSpan class illustrates why encapsulation is essential to enforcing conditions about the class
  • GOOD DESIGN = RIGOROUS CODE

Another example:

  • Polar coordinate points (r, theta)

Chapter 8 Summary

Deliverables

Classes: basics

  • Blueprint
  • Class vs object
  • State and behavior
  • Encapsulation and abstraction
  • Basic class syntax

State and behavior:

  • Class fields
  • Class methods
  • Class constructors
  • Class encapsulation
  • Fields: implicit parameters
  • Fields: getParam()/setParam()
  • toString()

Object initialization:

  • Objects are collections are data
  • Syntax of how to initialize
  • Protecting data from user
  • Default constructor
  • Common syntax errors
  • This keyword
  • Multiple constructors
  • Memory and reference
  • How this/constructors fit into this all

Encapsulation:

  • Hide details, protect data
  • Private fields - really protect data
  • BankAcct example - these are not just made up problems, they are REAL!
  • Syntax for private variables
  • Class invariants and rigorously enforcing conditions
  • Rigor requires encapsulation
  • Good code = trustworthy code


Chapter 8 Code

Lecture Code

Worksheet Code

Polynomial worksheet

  • Implement a polynomial object, use an array
  • Implement an add, evaluate, and toString method

Chapter 8 Homework

HW Questions

(Recommended) Self-check problems: #7, #10, #15, #18, #21, #26

(Required) Exercises: #3, #4, #5, #6, #14, #15, #16

(Required) Projects: (none)

HW Details

Self-check:

  • 7 - create Name class, first/middle/last
  • 10 - distance method to Point object
  • 15 - tSoString method to Name class
  • 18 - constructor problems
  • 21 - constructor to Point class accepting Point
  • 26 - encapsulate Name class

Exercises:

  • 3 - add manhattanDistance() method to Point class
  • 4 - add isVertical() method to Point class
  • 5 - add slope() method to Point class
  • 6 - add isCollinear() method to Point class
  • 14 - Line class between two points, implement specified constructors and methods
  • 15 - add getSlope() method to Line class
  • 16 - add Line constructor

Projects:

  • none

Chapter 8 Goodies

Profiles

Puzzle 8

Puzzles/Fall 2016/Puzzle 8

Quotes

Flags

http://design.tutsplus.com/articles/40-dark-and-futuristic-photoshop-effects--psd-291