Writing New Java Classes 15-121 Fall 2020 Margaret Reid-Miller - - PowerPoint PPT Presentation
Writing New Java Classes 15-121 Fall 2020 Margaret Reid-Miller - - PowerPoint PPT Presentation
Writing New Java Classes 15-121 Fall 2020 Margaret Reid-Miller Comments How was the Lab? Homework2: questions? install in Eclipse? Quiz will be available tomorrow and due on Sunday. I will send email and post on Piazza. Next
Comments
- How was the Lab?
- Homework2: questions? install in Eclipse?
- Quiz will be available tomorrow and due on
- Sunday. I will send email and post on Piazza.
- Next Monday, Margaret's office hours will be
from 12:00pm-2:00pm
Fall 2020 15-121 (Reid-Miller) 2
Today
- OOP terminology: classes and objects
- GiftCard class
- Alternator class exercises
Fall 2020 15-121 (Reid-Miller) 3
- How do we call a static method?
. ( ) method-name parameters
- How do we call a non-static method?
__ . ___ ( __ )
method-name parameters
- How do we call a constructor?
( ) parameters
Fall 2020 15-121 (Reid-Miller) 4
class name
- bject expression
new class-name
Can we write a method that returns multiple values?
- We can bundle together data of the same type in an
array and return the array.
- But even better, we can bundle together data of
different types in an object and return the object.
- Objects allows us to group related data and define
new data types.
Fall 2020 15-121 (Reid-Miller) 5
Object-Oriented Programming
- The idea is to divide an application into small
reusable objects.
- Think of them as the nouns that describe the
application.
- Then build the application from reusable
components.
- e.g., we build a car from various components
(wheels, doors, engine…)
Fall 2020 15-121 (Reid-Miller) 6
We define new object types by defining classes.
A class definition is like a blueprint for objects.
- We can create many instances of a class (objects)
from a class.
- The differences among these objects are values of its
attributes.
- For example, a class Student would define
attributes common to students:
- name, andrewId, courses enrolled….
but each object would have its own values for these attributes.
Fall 2020 15-121 (Reid-Miller) 8
Fall 2020 15-121 (Reid-Miller) 9
A Java class definition contains fields, constructors, and methods.
- fields store data. Often we cannot access
them directly outside the class.
- constructor(s) initialize all the fields.
- methods interact with the fields, either to
supply or modify them.
Fall 2020 15-121 (Reid-Miller) 10
Fields (instance variables) define an
- bject’s properties.
Example: An object from an GiftCard class might have the following fields:
- the name of the store
- the dollar value of the card.
- Once an object is created, each field has some value.
- These values define the current state of the object
and describe the current condition of the object.
Fall 2020 15-121 (Reid-Miller) 11
Fields
public class GiftCard { // Fields: The object state private String store; // Name of the store private double balance; // The current dollar value // Methods: The object behaviors }
Fields are usually private:
- visible to methods in the same class and
- hidden to methods in other classes.
By being private, we don't allow other classes to modify the fields directly or expose how the data is maintained.
initial capital
GiftCard class
Fall 2020 15-121 (Reid-Miller) 12
An Shopping application (client) can create Giftcard objects.
Use the new operator to instantiate (create) the object, followed by a call to the class constructor. The new operator returns a reference to the new
- bject.
For example in the main method we might write:
GiftCard macys = new GiftCard("Macy's", 100);
store balance
GiftCard
100
macys
String
Macy's
Shopping class
Fall 2020 15-121 (Reid-Miller) 13
Constructors initializes all the fields
- f the object.
public GiftCard(String storeName, double dollars) { store = storeName; balance = dollars; // Initial balance }
NOTE: For each parameter, we often use a name different from the field name to distinguish the two.
GiftCard class
Fall 2020 15-121 (Reid-Miller) 14
Constructors are like methods with two differences:
- 1. There is no return type.
- The object reference returned always has the
type of the class.
- 2. The name of the constructor is always the name of
the class.
- Like methods, any Java statement can be in the body
- f the constructor. For example, it might check that
the parameter dollars is positive.
Fall 2020 15-121 (Reid-Miller) 15
You can have more than
- ne constructor.
- Constructors can be overloaded:
Each constructor has a different parameter list.
- For example, some may supply default values for
fields that have no corresponding parameter.
public GiftCard(String storeName) { store = storeName; balance = 25.0; // Default balance }
GiftCard class
Fall 2020 15-121 (Reid-Miller) 16
The behaviors of an object are defined by its (instance) methods
- The methods that define the interface to an object
are usually public. These are the methods given in the Application Programmer Interface (API).
- The program code that creates and uses these
- bjects, called the client code, is now more
expressive and concise.
- The client simply asks the objects to perform their
behaviors (i.e., the objects provide a service).
Fall 2020 15-121 (Reid-Miller) 17
Accessors
- Accessors are methods that access an
- bject’s state without changing the state.
Examples:
public String getStoreName() { return store; } public double getBalance() { return balance; }
Accessors should be defined as public (visible by methods in every class).
Names often begin with “get”
GiftCard class
No static keyword
Fall 2020 15-121 (Reid-Miller) 20
Mutators
- Mutators are methods that can change an object’s
state.
public void buyGoods(double cost) { if (cost <= balance) { balance -= cost; } }
Mutators should be defined as public (visible to methods of every class).
GiftCard class
Fall 2020 15-121 (Reid-Miller) 21
Mutators should maintain class invariants
- Mutators should ensure that the object’s state stays
consistent with what the object is modeling, e.g., the gift card balance never goes negative. In another class: macys.buyGoods(10.0); updates the balance but macys.buyGoods(100000.0); doesn't.
Shopping class
Fall 2020 15-121 (Reid-Miller) 22
Sample Client Program
public class Shopping { public static void main(String[] args){ GiftCard macys = new GiftCard("Macy's", 100.0); GiftCard target = new GiftCard("Target", 50.0);
Shopping class
Each object has its own copy of the fields.
100.0 name balance GiftCard String Macy's macys String Target target 50.0 name balance GiftCard
Sample Client Program (cont'd)
Fall 2020 15-121 (Reid-Miller) 23
if (macys.getBalance() >= 42) { macys.buyGoods(42); } else { System.out.print("can't purchase, " + "insufficient funds"); } if (target.getBalance() < 10){ System.out.println("target card getting low"); } } // end main } // Shopping class
Shopping class
Fall 2020 15-121 (Reid-Miller) 24
Exercise: Write a Class Based on Its Use
Example: Using an alternator object
An Alternator object alternates between two integer values.
public static void main (String[] args) { Alternator alt3 = new Alternator(3, 6); System.out.println(alt3.alternate()); // prints 3 System.out.println(alt3.alternate()); // prints 6 // Method both changes state and accesses state! System.out.println(alt3.alternate()); // prints 3 System.out.println(alt3.alternate()); // prints 6 }
Fall 2020 15-121 (Reid-Miller) 25
AlternatorTester class
An Alternator object alternates between two integer values.
To write the Alternator class start by determining the fields and ask:
- What does an object need to remember?
- What are its attributes/properties?
How should we declare a fields? _________ _____ ________; type name
Fall 2020 15-121 (Reid-Miller) 26
private
Alternator class
Alternator class
- What is the main purpose of the constructor?
- How do you declare a constructor?
public ______________( . . . ) { //What should usually go here?
Fall 2020 15-121 (Reid-Miller) 27
initialize the fields class name field1 = …; field2 = …;
More on writing classes
Fall 2020 15-121 (Reid-Miller) 28
Fall 2020 15-121 (Reid-Miller) 29
Every class should have toString()method.
- A toString() method returns a string that
represents the current state of the object
public String toString() { return "store = " + store + " balance = " + balance; } Required signature
GiftCard class
Fall 2020 15-121 (Reid-Miller) 30
Often toString() is used for debugging.
public class Shopping { public static void main(String[] args){ target = new GiftCard("Target"); target.buyGoods(10.50); System.out.println("target: " + target); Java invokes toString() on objects in
- print statements and
- string concatenation expressions.
Shopping class
Fall 2020 15-121 (Reid-Miller) 31
Every class should have an equals()method.
An equals() method compares two objects and returns true if they have the same state and false
- therwise.
public boolean equals(GiftCard other) { if (other == null) return false; return store.equals(other.store) && balance == other.balance; }
In another class, call this method with two objects
target.equals(macys)
GiftCard class
Use dot to access an object’s fields.
Fall 2020 15-121 (Reid-Miller) 32
The this Reference
- The reserved word this allows an object to refer to
itself within its class. (It is sometimes called the implicit parameter.)
public GiftCard(String name, float dollars) { this.name = name; … }
shadows the field field
public boolean equals(GiftCard other) { return this.name.equals(other.name) && … } Usage: if (target.equals(macys)) …
GiftCard class
Encapsulation hides object data and method implementations.
Who knows how to use a radio? Who knows how to build a radio from low-level electronic parts?
- A client (user) only needs to know what the object
does (its interface).
- A server (implementor) decides how the object does
it. To maintain object data dependencies and maximize reusability the server should
- not allow the client direct manipulation of the data
- nor expose the details of the implementation.
Fall 2020 15-121 (Reid-Miller) 33
Encapsulation reduces data dependency and maximize reusability.
- Advantages:
- Reduces complexity for the client.
- If you change the object’s underlying data
structure or algorithms, the client works as before.
- Since there is no direct access to fields, you can
ensure internal data dependencies (class invariants) are maintained.
Fall 2020 15-121 (Reid-Miller) 34
Classes (and their parts) have visibility modifiers:
- public: accessible to everyone
- protected: inside package, inside class,
inside subclass
- package-private (default, no modifier
used): inside package, inside class
- private: accessible only within the class
Fall 2020 15-121 (Reid-Miller) 35
Data fields are usually private
Data (fields):
- Whatever the object needs to store
- Available to clients via “getter” and “setter”
methods.
- Are private to encapsulate the object data
from clients and to ensure class invariants.
Fall 2020 15-121 (Reid-Miller) 36
Public vs Private Methods
public: Only those methods that are part of the interface (the methods the client can call).
- They can’t assume the client will supply correct
arguments.
- These methods must ensure that the pre- and post-
conditions are met and post-conditions maintain the class invariants. private: “helper” methods inside the class
- Since clients cannot call these methods, and the
server calls meet the pre-conditions, these methods need not check the pre-conditions.
Fall 2020 15-121 (Reid-Miller) 37