Title: OO Concepts
1OO Concepts
2Chapter 3
3Object-Oriented Concepts (review)
- Encapsulation hiding unimportant details
- Black box something that magically does its
thing - Abstraction taking away inessential features
- Example car
- if engine control module fails, replace it
- mechanic can provide inputs, test outputs
- doesnt need to know how it works
- OO challenge finding the right abstractions
(what black boxes do we need to solve the
problem at hand?)
4Object-Oriented Concepts (review)
- How would you represent
- a bank account?
- a book?
- a library?
- a customer?
- an oil field?
- a mutual fund?
- an employee?
5BankAccount
- See Eclipse notes for example of creating class
with comments - As in C, constructors have name of class, can
be overloaded - Instance fields should be made private, accessors
and modifiers (getters/setters) are used - Additional methods are defined as needed
6More on Variables
- Instance variables
- each object has its own copy (as in C)
- objects are automatically garbage collected
(unlike C!) - fields are initialized with a default value
(e.g., 0, null) if not explicitly set in
constructor. Still good to do your own
initialization. - NullPointerException if you forget to call new
- Local variables
- must be explicitly initialized
- only exist inside method (as in C)
7javadoc comments
- Remember the API had a standard format.
User-defined classes can easily create html
documentation in that same format, by inserting
comments that meet certain specifications - Start with /
- First sentence describes purpose
- _at_ tags specify information (e.g., _at_param,
_at_return, _at_throws, _at_author, _at_version) - run javadoc from command line or Eclipse to
generate html pages
8Chapter 8
- Class design, UML, cohesion coupling, static
fields and methods
9Choosing Classes
- Common class names are nouns, methods names are
verbs - class BankAccount, methods deposit, withdraw etc.
- class CashRegister, methods enterPayment,
recordPurchase, etc. - Classes may also be actors that do some type of
work for you - Scanner scans stream for numbers and strings
- Random generates random numbers
- Utility class may have no objects, but exists to
provide static methods and constants - Math class
- Some classes just exist to start a program
(degenerate classes)
10Choosing Classes (continued)
- Which of the following are good classes?
- ComputePaycheck
- PaycheckProgram
- Paycheck
- ChessBoard
- MoveChessPiece
- A class should represent a single concept
11Cohesion and Coupling
- Cohesion All public methods (i.e., the public
interface) should be closely related to the
single concept the class represents - Coupling Number of dependencies between classes
12Coupling
low coupling
high coupling
13UML Dependency Relationship
Unified Modeling Language Booch, Jacobson,
Rumbaugh
In a class diagram, dependency is a dashed line
with a shaped open arrow that points to dependent
class. (i.e., CashRegister depends on Coin)
CashRegister
Coin
Note direction of arrow CashRegister depends on
Coin Coin is independent
14Static Methods
- Also known as class method
- Does not operate on an object, so it has only
explicit parameters - Example
- public class Financial
-
- public static double percentOf(double p, double
a) -
- return (p/100) a
-
-
- double tax Financial.percentOf(taxRate, total)
All data is passed in, no owned variables
Call with class name, not instance
15Static Fields
- Used to store values outside any particular
object - public class BankAccount
-
- private double balance
- private int lastAssignedNumber 1000
- // No
-
-
- should be
- private static int lastAssignedNumber 1000
16Instance vs Static vs Local Which to Use?
- Use instance variables for data that belong to
one instance of the class and will be operated on
by multiple methods - Use local variables for temporary calculations
within a method - Use static ONLY for constants and when methods
will be called with no object
17Intance vs Local vs Static Example
- public class Financial
- public static double percentOf(double p, double
a) -
- return (p/100) a
-
-
- public class BankAccount
- private double balance
- private double intRate
- // addInterest updates balance returns amt of
interest - public double addInterest()
- double interest balance intRate
- balance interest
- return interest
-
- Common errors
- Making all variables instance, even if only used
in one function. - Making all variables static like using globals!
18Chapter 9
19Interfaces for Code Reuse
- Interface specifies common set of operations
- All methods are abstract (like prototypes), no
implementation. Must be public. - Interface may have constants, but no instance
fields (never instantiate an interface directly) - Other classes can then implement that interface
20Interface Example
- public interface Measureable
-
- double getMeasure()
public class Coin implements Measurable
public double getMeasure() return
value . . .
keyword public required, default is package
- public class BankAccount implements Measurable
-
- public double getMeasure()
-
- return balance
-
- . . .
-
Can implement more than one interface!
21Interface Example, continued
- public class DataSet
-
- public void add(Measurable x)
-
- sum sum x.getMeasure()
- if (count 0
- max.getMeasure() lt x.getMeasure())
- max x
- count
-
- public Measureable getMaximum()
-
- return max
-
- private double sum
- private Measurable max
- private int count
22Interface Example, continued
- BankAccount account new BankAccount(1000)
- Measurable x account // OK to convert
- Coin dime new Coin(0.1, dime)
- x dime // Also OK notice we dont know type
of - // x, just that it implements Measurable, so it
is - // OK to call getMeasure. May do cast if you are
- // sure of the type
- DataSet coinData new DataSet()
- coinData.add(new Coin(0.25, quarter)
- Measurable max coinData.getMaximum()
- String coinName max.getName() // Error
- Coin maxCoin (Coin) max // Error if youre
wrong! - String coinName max.getName()
- Measurable x new Rectangle(5, 10, 20, 20)
//not OK
23Polymorphism
- How is correct method executed?
- Measurable x new BankAccount(1000)
- double m x.getMeasure()
- x new Coin(0.1, dime)
- m x.getMeasure()
- JVM locates correct method. What did we do in
C? - Overloading method early binding (e.g., default
vs 1-parameter constructor static) - Polymorphism late binding (dynamic)
24UML Diagram
stereotype indicator
ltltinterfacegtgt Measurable
DataSet
uses (open arrow tip)
is-a (triangular tip)
BankAccount
Coin
25Chapter 10
26Inheritance Basics
- Models is-a relationship, same as C
- requires extends keyword
- All classes are children of class Object
- Object has several methods that are frequently
overridden - toString returns a string that describes the
state of the object, automatically called by
System.out.println(objectRef) - clone creates a deep copy of an object
- equals does a field-by-field comparison, returns
boolean result
27Simple Inheritance Example
- public class BankAccount
-
- public BankAccount()
- balance 0
-
- public BankAccount(double initialBalance)
- balance initialBalance
-
- public void deposit(double amount)
- double newBalance balance amount
- balance newBalance
-
- public void withdraw(double amount)
- double newBalance balance - amount
- balance newBalance
-
- public double getBalance()
- return balance
-
could be protected
28Simple Inheritance Example
- class SavingsAccount extends BankAccount
-
- public SavingsAccount(double balance, double
rate) -
- super(balance) // calls parent constructor
- interestRate rate
-
- void addInterest()
-
- // use getters/setters unless protected
- double interest getBalance() interestRate
/ 100 - deposit(interest)
-
- private double interestRate
cant directly update balance if private
29UML for Inheritance
Object
BankAccount -balance deposit(double) withdraw(doub
le) getBalance
should be hollow triangle tip
BankAccount
SavingsAccount
SavingsAccount -interestRate addInterest(double
30Can have Inheritance Hierarchy
JComponent
JPane
JTextComponent
JLabel
AbstractButton
JToggleButton
JButton
JTextField
JTextArea
JCheckBox
JRadioButton
31More on Inheritance
- SavingsAccount collegeFund new
SavingsAccount(1000, 0.1) - BankAccount anAccount collegeFund
- Object anObject collegeFund
- collegeFund.addInterest() // OK
- anAccount.addInterest() //not OK
32Typecasts
- If you know that a reference contains a specific
type of object, you can perform a cast (will be
an exception if youre wrong) - BankAccount myAccount (BankAccount) anObject
- Can use instanceof to test class type
- if (anObject instanceof BankAccount)
-
- BankAccount myAccount (BankAccount) anObject
-
33Polymorphism
- In Java, method calls are always determined by
the type of the actual object, not the type of
the object reference (unlike C, where virtual
keyword is needed)
34Abstract Classes
- Concept same as C, use in same types of
situations (e.g., force subclasses to define
behavior) - Requires use of abstract keyword
- As in C, you cant initialize objects of an
abstract type. But you can initialize a variable
of an abstract class to a subclass.
public abstract class BankAccount public
abstract void deductFees() . .
. BankAccount anAccount anAccount new
BankAccount() // ERROR anAccount new
SavingsAccount() // OK (deductFees defined)
35Final Methods and Classes
- May occasionally want to prevent others from
creating subclasses or overriding methods - public final class String . . .
- public final boolean checkPassword(String
password) . . .
36Access control
- public like C, good for constants
- private like C, good for instance fields
- protected like C but extends to package,
convenient for inheritance - package
- all methods of classes in the same package have
access - this is the default! (easy to forget)
- OK if several classes in package collaborate, but
generally inner classes are better, packages are
not secure (anyone can add a class to the
package) - public class BankAccount
- double balance // package access
- . . .
37Object Method Examples toString
class object describes class properties
- public class BankAccount
-
- public String toString()
- return getClass().getName() balance
-
- . . .
-
- public class SavingsAccount
-
- public String toString()
- return super.toString() Rate
- interestRate
-
- . . .
-
call to parent class
38Object Method Examples equals
- public boolean equals(Object otherObject)
-
- if (otherObject null) return false
- if (getClass() ! otherObject.getClass())
- return false
- BankAccount account (BankAccount) otherObject
- return balance account.balance
- // should call super.equals first if you write
an - // equals for a subclass
- // instanceof sometimes used instead of
- // getClass(), but it would return true for a
- // subclass
What happens if you dont override equals?
39Object Method Examples clones
- Read advanced topic 10.6 if you need to write a
clone method