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 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? . ( ) class name method-name parameters • How do we call a non-static method? __ . ___ ( __ ) object expression method-name parameters • How do we call a constructor? new ( ) class-name parameters Fall 2020 15-121 (Reid-Miller) 4
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
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) 9
Fields ( instance variables ) define an object’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) 10
GiftCard class Fields initial capital 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. Fall 2020 15-121 (Reid-Miller) 11
Shopping class 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 object. For example in the main method we might write: GiftCard macys = new GiftCard( " Macy's " , 100); GiftCard String macys store Macy's 100 balance Fall 2020 15-121 (Reid-Miller) 12
GiftCard class Constructors initializes all the fields of 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. Fall 2020 15-121 (Reid-Miller) 13
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 of the constructor. For example, it might check that the parameter dollars is positive. Fall 2020 15-121 (Reid-Miller) 14
GiftCard class You can have more than one 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 } Fall 2020 15-121 (Reid-Miller) 15
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 objects, 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) 16
GiftCard class Accessors • Accessors are methods that access an object’s state without changing the state. Examples: public String getStoreName() { return store; Names often } begin with “get” No static keyword public double getBalance() { return balance; } Accessors should be defined as public (visible by methods in every class). Fall 2020 15-121 (Reid-Miller) 17
GiftCard class 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). Fall 2020 15-121 (Reid-Miller) 20
Shopping class 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. Fall 2020 15-121 (Reid-Miller) 21
Shopping class Sample Client Program Each object has its own copy of the public class Shopping { fields. public static void main(String[] args){ GiftCard macys = new GiftCard("Macy ' s", 100.0); GiftCard target = new GiftCard("Target", 50.0); GiftCard String macys name Macy ' s 100.0 balance GiftCard String target name Target 50.0 balance Fall 2020 15-121 (Reid-Miller) 22
Shopping class Sample Client Program (cont'd) 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 Fall 2020 15-121 (Reid-Miller) 23
Exercise: Write a Class Based on Its Use Fall 2020 15-121 (Reid-Miller) 24
AlternatorTester class 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
Alternator 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? _________ _____ ________; private type name Fall 2020 15-121 (Reid-Miller) 26
Alternator class • What is the main purpose of the constructor? initialize the fields • How do you declare a constructor? class name public ______________( . . . ) { //What should usually go here? field1 = …; field2 = …; Fall 2020 15-121 (Reid-Miller) 27
More on writing classes Fall 2020 15-121 (Reid-Miller) 28
GiftCard class Every class should have toString() method. • A toString() method returns a string that represents the current state of the object Required signature public String toString() { return " store = " + store + " balance = " + balance; } Fall 2020 15-121 (Reid-Miller) 29
Shopping class 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. Fall 2020 15-121 (Reid-Miller) 30
GiftCard class Every class should have an equals() method. An equals() method compares two objects and returns true if they have the same state and false otherwise. public boolean equals(GiftCard other) { if (other == null) return false; return store.equals(other.store) && balance == other.balance; } Use dot to access an object’s fields. In another class, call this method with two objects target.equals(macys) Fall 2020 15-121 (Reid-Miller) 31
Recommend
More recommend