1 user-defined classes the string class is a pre-defined class that is provided by the java...

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

Upload: bobby-baney

Post on 31-Mar-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 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

11

User-Defined ClassesUser-Defined Classes

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

Page 2: 1 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

22

Classes dan ObjectsClasses dan Objects

A Class in object-oriented modeling is a A Class in object-oriented modeling is a template for creating objects.template for creating objects.

An object is an instance of a class.An object is an instance of a class.

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

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

Page 3: 1 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

33

Contoh – PhoneCard classContoh – PhoneCard class

The following PhoneCard class represents The following PhoneCard class represents a pre-paid mobile phone card.a pre-paid mobile phone card.

name of the class

attributes (data that is to be stored)

methods

PhoneCard

phoneNumberbalance

PhoneCard( )getPhoneNumber( )getBalance( )setPhoneNumber( )setBalance( )makeCall( )topUp( )toString( )

Page 4: 1 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

44

AttributAttribut

The attributes The attributes phoneNumberphoneNumber and and balance balance are encapsulated with each are encapsulated with each PhoneCardPhoneCard object. object.

The values of these attributes will differ with The values of these attributes will differ with each instance of each instance of PhoneCardPhoneCard mymy PhoneCard may have phoneNumber 012- PhoneCard may have phoneNumber 012-

1122334 and balance of RM100.001122334 and balance of RM100.00 youryour PhoneCard may have phoneNumber 011- PhoneCard may have phoneNumber 011-

1093823 and balance of RM3.501093823 and balance of RM3.50

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

Page 5: 1 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

55

PhoneCard MethodsPhoneCard Methodspublic PhoneCard(String phoneNumber, double balance)public PhoneCard(String phoneNumber, double balance)

the the constructorconstructor, , which creates a new which creates a new PhoneCardPhoneCard object. object.public String getPhoneNumber()public String getPhoneNumber()

returns the value of returns the value of phoneNumberphoneNumberpublic double getBalance()public double getBalance()

returns the value of returns the value of balancebalancepublic void setPhoneNumber(String newPhoneNum)public void setPhoneNumber(String newPhoneNum)

sets the value of sets the value of phoneNumberphoneNumber to to newPhoneNumnewPhoneNumpublic void setBalance(double newBalance)public void setBalance(double newBalance)

sets the value of sets the value of balancebalance to to newBalancenewBalancepublic void topUp(double amount)public void topUp(double amount)

tops up the PhoneCard's tops up the PhoneCard's balancebalance by by amountamount..public boolean makeCall(double duration, double costPerMin)public boolean makeCall(double duration, double costPerMin)

reduces the PhoneCard's reduces the PhoneCard's balancebalance by the cost of the call. by the cost of the call.public String toString()public String toString()

returns a String containing information about the PhoneCard object.returns a String containing information about the PhoneCard object.

Page 6: 1 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

66

Bagaimana objects dibuatBagaimana objects dibuat

PhoneCard myCard = new PhoneCard("012-1122334", 20);

The constructor call creates a new The constructor call creates a new object:object:

myCard

Page 7: 1 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

77

Bagaimana objects dibuatBagaimana objects dibuat

PhoneCard myCard = new PhoneCard("012-1122334", 20);PhoneCard extraCard = new PhoneCard("012-1234567", 10);

You can create many objects, each with its You can create many objects, each with its own reference:own reference:

extraCardmyCard

Page 8: 1 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

88

extraCardmyCard

Menjalankan Method ObyekMenjalankan Method Obyek

System.out.println(extraCard.getBalance());

We invoke a method for the object by We invoke a method for the object by specifying the right object and calling the specifying the right object and calling the appropriate method with the parameters.appropriate method with the parameters.

Invokes this method for the object called extraCard

Page 9: 1 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

99

Membuat class PhoneCardMembuat class PhoneCard

You can write the class provider for the You can write the class provider for the PhoneCardPhoneCard class by specifying: class by specifying: the instance variablesthe instance variables the class methods:the class methods:

ConstructorsConstructorsWriter methodsWriter methodsReader methodsReader methodsQuery methodsQuery methodsCustom methodsCustom methods

Page 10: 1 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

1010

Instance VariablesInstance Variables

The The instance variablesinstance variables are the variables are the variables which hold data specific to the class, or which hold data specific to the class, or the attributes.the attributes.For the PhoneCard class, they are:For the PhoneCard class, they are: phoneNumberphoneNumber balancebalance

The instance variables are declared as The instance variables are declared as privateprivate so that the information is so that the information is hiddenhidden from other classes. from other classes.

Page 11: 1 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

1111

Definisi ClassDefinisi Class

public class PhoneCard{

// attributesprivate String phoneNumber;private double balance;

//methods go here…

}

PhoneCard

phoneNumberbalance

PhoneCard( )getPhoneNumber( )getBalance( )setPhoneNumber( )setBalance( )makeCall( )topUp( )toString( )

class in UML notation

class in Java

Page 12: 1 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

1212

ConstructorsConstructors

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

sets instance variables to default valuessets instance variables to default values Constructor with arguments which sets Constructor with arguments which sets

instance variables to the values of the instance variables to the values of the arguments passed in.arguments passed in.

Page 13: 1 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

1313

Contoh – Default ConstructorContoh – Default Constructorpublic class PhoneCard{

// attributesprivate String phoneNumber;private double balance;

// default Constructor, no argumentspublic PhoneCard(){

phoneNumber = "" // empty stringbalance = 0.0;

}

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

constructor has the same name as the class, and no return type.

Page 14: 1 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

1414

Constructor dengan ArgumentsConstructor dengan Arguments

public class PhoneCard{

// attributesprivate String phoneNumber;private double balance;

// Constructor with argumentspublic PhoneCard(String inNumber, double inBalance){

phoneNumber = inNumber;if (inBalance > 0) // check validity

balance = inBalance;else

balance = 0.0;}

arguments used to initialize instance variables

Page 15: 1 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

1515

Reader/ Accessor MethodsReader/ Accessor Methods

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

Page 16: 1 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

1616

Reader/accessor MethodsReader/accessor Methods(getters)(getters)

public class PhoneCard{

// attributesprivate String phoneNumber;private double balance;

//accessor methodspublic String getPhoneNumber(){

return phoneNumber;}

public double getBalance(){

return balance;}

This getter 'gets' the phone Number

The return type is String

This getter 'gets' the balance

phone number returned

the double value balance returned

Page 17: 1 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

1717

Writer/Mutator MethodsWriter/Mutator Methods(setters)(setters)

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

Page 18: 1 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

1818

Writer MethodsWriter Methodspublic class PhoneCard{

// attributesprivate String phoneNumber;private double balance;

//writer methodspublic void setPhoneNumber(String newNumber){

phoneNumber = newNumber;}

public void setBalance(double newBalance){

if (newBalance > 0)balance = newBalance;

}

This setter 'sets' the phone number to newNumber

Some validation may be performed.Return type is void.

Page 19: 1 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

1919

Query MethodsQuery Methods

The class provider usually has a The class provider usually has a toStringtoString method that returns a String method that returns a String containing information about the object's containing information about the object's current data.current data.public class PhoneCard

{// attributesprivate String phoneNumber;private double balance;

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

Page 20: 1 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

2020

Standard MethodsStandard Methods

We say that the We say that the Constructor, Constructor, Getter,Getter, Setter andSetter and QueryQuery

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

Page 21: 1 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

2121

Custom Methods or ServicesCustom Methods or Services

When we create a new class provider, that class When we create a new class provider, that class will probably have methods that provide special will probably have methods that provide special services.services.For the PhoneCard class, we want to allow For the PhoneCard class, we want to allow PhoneCard objects to:PhoneCard objects to: be 'topped-up': that is, to increase the balance in the be 'topped-up': that is, to increase the balance in the

cardcard record that calls have been made: to decrease the record that calls have been made: to decrease the

balance in the card.balance in the card.

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

Page 22: 1 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

2222

Topping Up the PhoneCardTopping Up the PhoneCardThe topUp method takes in one argument The topUp method takes in one argument representing the top-up amount and adds it representing the top-up amount and adds it to the existing balance if it is non-negative.to the existing balance if it is non-negative.public class PhoneCard{

// attributesprivate String phoneNumber;private double balance;

// Method to top up the balance by amountpublic void topUp(double amount){

if (amount > 0)balance += amount;

}

Page 23: 1 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

2323

Making a Call with the PhoneCardMaking a Call with the PhoneCard

The makeCall method takes in two arguments: The makeCall method takes in two arguments: one representing the duration of the call in one representing the duration of the call in minutes and one representing the cost of the call minutes and one representing the cost of the call per minute. per minute.

The cost is calculated and subtracted from the The cost is calculated and subtracted from the balance. If the balance becomes negative, the balance. If the balance becomes negative, the balance is set to zero and the boolean value balance is set to zero and the boolean value false is returned. Otherwise, the boolean value false is returned. Otherwise, the boolean value true is returned to indicate a successful call true is returned to indicate a successful call made.made.

Page 24: 1 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

2424

makeCallmakeCall method method// Method to record calls made, thus reducing balancepublic 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; // set to zeroreturn false;

}return true;

}

Page 25: 1 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

2525

System - specific codeSystem - specific code

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

Page 26: 1 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

2626

Sample Class ProviderSample Class Provider

The PhoneCard class we have The PhoneCard class we have defined can now work.defined can now work.

See the class PhoneCard.java for the See the class PhoneCard.java for the complete class definition.complete class definition.

Test the class using Test the class using TestPhoneCard.classTestPhoneCard.class

Page 27: 1 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

2727

LatihanLatihanWrite the class provider for a class called Rectangle.Write the class provider for a class called Rectangle.Rectangles have Rectangles have

lengthlength widthwidth

Write the Write the default constructor: length and width set to zerodefault constructor: length and width set to zero constructor with arguments to set the length and width as long as they constructor with arguments to set the length and width as long as they

are non-negativeare non-negative reader methodsreader methods writer methodswriter methods method to calculate the area method to calculate the area method to calculate the perimetermethod to calculate the perimeter toString methodtoString method

Page 28: 1 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

2828

LatihanLatihan

Now test your Rectangle class using a driver Now test your Rectangle class using a driver program.program. Create one rectangle using the no-args ConstructorCreate one rectangle using the no-args Constructor Create another rectangle using the arguments 5.5 for Create another rectangle using the arguments 5.5 for

length and 7.8 for width.length and 7.8 for width. Set the length and width of the first rectangle using Set the length and width of the first rectangle using

the writer methodsthe writer methods Find and display the perimeter of both rectangles.Find and display the perimeter of both rectangles. Display information about the rectangle with the larger Display information about the rectangle with the larger

area.area.

Page 29: 1 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

2929

The Circle classThe Circle classA Circle class provider has been defined: it can be A Circle class provider has been defined: it can be used to create Circle objects. Test the Circle class:used to create Circle objects. Test the Circle class:

public Circle()• creates a Circle object with radius 0.0public Circle(double radius)• creates a Circle object with the required radius.public double getRadius()• returns the radius of the Circlepublic void setRadius(double radius)• sets the radius of the Circle to the required

valuepublic double area()• returns the area of the Circlepublic double circumference()• returns the circumference of the Circle.

Circle

radiusname

Circle()getRadius()setRadius()area()circumference()

Page 30: 1 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

3030

Other ClassesOther Classes

What data and methods would you What data and methods would you define for the following objects?define for the following objects? Bank AccountBank Account StudentStudent Library BookLibrary Book CarCar

Write the class providers.Write the class providers.