Sie sind auf Seite 1von 30

User-Defined Classes

The String class is a pre-defined class that is provided by the Java Designer. Sometimes programmers would like to create their own reference data types, or class definitions. Programmers will write a class provider to implement a reference data type. A class provider is like a program that we have been writing, except that it does not have a main method.
1

Classes dan Objects


A Class in object-oriented modeling is a template for creating objects. An object is an instance of a class. Objects

know things (data) know how to do things (methods)

The Class provider defines the data and the methods for the class.
2

Contoh PhoneCard class


The following PhoneCard class represents a pre-paid mobile phone card.
PhoneCard phoneNumber balance PhoneCard( ) getPhoneNumber( ) getBalance( ) setPhoneNumber( ) setBalance( ) makeCall( ) topUp( ) toString( )

name of the class

attributes (data that is to be stored)

methods

Attribut
The attributes phoneNumber and balance are encapsulated with each PhoneCard object. The values of these attributes will differ with each instance of PhoneCard

my PhoneCard may have phoneNumber 0121122334 and balance of RM100.00 your PhoneCard may have phoneNumber 0111093823 and balance of RM3.50

The attributes are usually private, which means they are not directly accessible.
4

PhoneCard Methods
public PhoneCard(String phoneNumber, double balance)

the constructor, which creates a new PhoneCard object. returns the value of phoneNumber returns the value of balance sets the value of phoneNumber to newPhoneNum sets the value of balance to newBalance tops up the PhoneCard's balance by amount. reduces the PhoneCard's balance by the cost of the call. returns a String containing information about the PhoneCard object.
5

public String getPhoneNumber()

public double getBalance()

public void setPhoneNumber(String newPhoneNum)

public void setBalance(double newBalance)

public void topUp(double amount)

public boolean makeCall(double duration, double costPerMin)

public String toString()

Bagaimana objects dibuat


The constructor call creates a new object:
PhoneCard myCard = new PhoneCard("012-1122334", 20);

myCard

Bagaimana objects dibuat


You can create many objects, each with its own reference:
PhoneCard myCard = new PhoneCard("012-1122334", 20); PhoneCard extraCard = new PhoneCard("012-1234567", 10);

myCard

extraCard

Menjalankan Method Obyek


We invoke a method for the object by specifying the right object and calling the appropriate method with the parameters.
System.out.println(extraCard.getBalance());
Invokes this method for the object called extraCard

myCard

extraCard

Membuat class PhoneCard


You can write the class provider for the PhoneCard class by specifying:

the instance variables the class methods: Constructors Writer methods Reader methods Query methods Custom methods
9

Instance Variables
The instance variables are the variables which hold data specific to the class, or the attributes. For the PhoneCard class, they are:

phoneNumber balance

The instance variables are declared as private so that the information is hidden from other classes.
10

Definisi Class
PhoneCard phoneNumber balance PhoneCard( ) getPhoneNumber( ) getBalance( ) setPhoneNumber( ) setBalance( ) makeCall( ) topUp( ) toString( )

public class PhoneCard { // attributes private String phoneNumber; private double balance; //methods go here

class in Java

class in UML notation


11

Constructors
Constructors are needed to create objects of the class. A Constructor is a method with the same name as the class. We may write two kinds of constructors:

Default Constructor, takes no arguments and sets instance variables to default values Constructor with arguments which sets instance variables to the values of the arguments passed in.
12

Contoh Default Constructor


public class PhoneCard { // attributes private String phoneNumber; private double balance; constructor has the same name as the class, and no return type.

// default Constructor, no arguments public PhoneCard() { phoneNumber = "" // empty string balance = 0.0; }

the constructor initializes the instance variables when a new PhoneCard object is created.
13

Constructor dengan Arguments


public class PhoneCard { // attributes private String phoneNumber; private double balance;

// Constructor with arguments public PhoneCard(String inNumber, double inBalance) { phoneNumber = inNumber; if (inBalance > 0) // check validity balance = inBalance; else balance = 0.0; }

arguments used to initialize instance variables

14

Reader/ Accessor Methods


Although the instance variables are declared private, they can still be retrieved via methods (within the class). Reader methods are used to retrieve the values of the instance variables. Reader methods are also known as getters because they are commonly named getXXX where XXX is the name of the instance variable.
15

Reader/accessor Methods (getters) public class PhoneCard


{ The return type is String

// attributes private String phoneNumber; private double balance;


//accessor methods public String getPhoneNumber() { return phoneNumber; } public double getBalance() { return balance; }

This getter 'gets' the phone Number

phone number returned

This getter 'gets' the balance

the double value balance returned

16

Writer/Mutator Methods (setters)


Similarly, the values held by the instance variables can be changed by using methods. Writer methods are used to change the values. Writer methods are also known as setters because they are commonly named setXXX where XXX is the name of the instance variable.
17

Writer Methods
public class PhoneCard { // attributes private String phoneNumber; private double balance; This setter 'sets' the phone number to newNumber //writer methods public void setPhoneNumber(String newNumber) { phoneNumber = newNumber; }

public void setBalance(double newBalance) { if (newBalance > 0) balance = newBalance; }

Some validation may be performed. Return type is void. 18

Query Methods
The class provider usually has a toString method that returns a String containing information about the object's public class PhoneCard current data. {
// attributes private String phoneNumber; private double balance;

// toString returns information about PhoneCard public String toString() { return phoneNumber + " has balance of " + balance; }
19

Standard Methods
We say that the

Constructor, Getter, Setter and Query

methods are standard methods because we expect them to be available for most class providers.
20

Custom Methods or Services


When we create a new class provider, that class will probably have methods that provide special services. For the PhoneCard class, we want to allow PhoneCard objects to:

be 'topped-up': that is, to increase the balance in the card record that calls have been made: to decrease the balance in the card.

We have to write methods to carry out the above functions.


21

Topping Up the PhoneCard


The topUp method takes in one argument representing the top-up amount and adds it to the existing balance if it is non-negative.
public class PhoneCard { // attributes private String phoneNumber; private double balance; // Method to top up the balance by amount public void topUp(double amount) { if (amount > 0) balance += amount; }
22

Making a Call with the PhoneCard


The makeCall method takes in two arguments: one representing the duration of the call in minutes and one representing the cost of the call per minute. The cost is calculated and subtracted from the balance. If the balance becomes negative, the balance is set to zero and the boolean value false is returned. Otherwise, the boolean value true is returned to indicate a successful call made.
23

makeCall method
// Method to record calls made, thus reducing balance public boolean makeCall(double duration, double costPerMin) { double cost = duration * costPerMin; if (cost > 0) balance -= cost; else return false; // invalid parameters if (balance < 0) { balance = 0; return false; } return true;

// set to zero

24

System - specific code


We should be careful not to use system-specific code when writing a class provider. For example, a statement containing System.out.println() only displays output to the console screen. This statement cannot be used when using the PhoneCard class in a GUI application or an Applet. This is why reader methods or query methods are used to obtain data. The driver program will then manipulate the data.
25

Sample Class Provider


The PhoneCard class we have defined can now work. See the class PhoneCard.java for the complete class definition. Test the class using TestPhoneCard.class

26

Latihan
Write the class provider for a class called Rectangle. Rectangles have length width Write the default constructor: length and width set to zero constructor with arguments to set the length and width as long as they are non-negative reader methods writer methods method to calculate the area method to calculate the perimeter toString method

27

Latihan
Now test your Rectangle class using a driver program.

Create one rectangle using the no-args Constructor Create another rectangle using the arguments 5.5 for length and 7.8 for width. Set the length and width of the first rectangle using the writer methods Find and display the perimeter of both rectangles. Display information about the rectangle with the larger area.
28

The Circle class


A Circle class provider has been defined: it can be used to create Circle objects. Test the Circle class:
public Circle()
Circle radius name Circle() getRadius() setRadius() area() circumference()
creates a Circle object with radius 0.0

public Circle(double radius)


creates a Circle object with the required radius.

public double getRadius()


returns the radius of the Circle

public void setRadius(double radius)


sets the radius of the Circle to the required value

public double area()


returns the area of the Circle

public double circumference()


returns the circumference of the Circle.
29

Other Classes
What data and methods would you define for the following objects?

Bank Account Student Library Book Car

Write the class providers.


30

Das könnte Ihnen auch gefallen