Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

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 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.

2 2 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 things (data) know how to do things (methods) know how to do things (methods) The Class provider defines the data and the methods for the class.

3 3 Contoh – PhoneCard class The following PhoneCard class represents a pre-paid mobile phone card. name of the class attributes (data that is to be stored) methods

4 4 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 and balance of RM my PhoneCard may have phoneNumber and balance of RM your PhoneCard may have phoneNumber and balance of RM3.50 your PhoneCard may have phoneNumber and balance of RM3.50 The attributes are usually private, which means they are not directly accessible.

5 5 PhoneCard Methods public PhoneCard(String phoneNumber, double balance) the constructor, which creates a new PhoneCard object. the constructor, which creates a new PhoneCard object. public String getPhoneNumber() returns the value of phoneNumber returns the value of phoneNumber public double getBalance() returns the value of balance returns the value of balance public void setPhoneNumber(String newPhoneNum) sets the value of phoneNumber to newPhoneNum sets the value of phoneNumber to newPhoneNum public void setBalance(double newBalance) sets the value of balance to newBalance sets the value of balance to newBalance public void topUp(double amount) tops up the PhoneCard's balance by amount. tops up the PhoneCard's balance by amount. public boolean makeCall(double duration, double costPerMin) reduces the PhoneCard's balance by the cost of the call. reduces the PhoneCard's balance by the cost of the call. public String toString() returns a String containing information about the PhoneCard object. returns a String containing information about the PhoneCard object.

6 6 Bagaimana objects dibuat PhoneCard myCard = new PhoneCard(" ", 20); The constructor call creates a new object: myCard

7 7 Bagaimana objects dibuat PhoneCard myCard = new PhoneCard(" ", 20); PhoneCard extraCard = new PhoneCard(" ", 10); You can create many objects, each with its own reference: extraCardmyCard

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

9 9 Membuat class PhoneCard You can write the class provider for the PhoneCard class by specifying: the instance variables the instance variables the class methods: the class methods:Constructors Writer methods Reader methods Query methods Custom methods

10 10 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 phoneNumber balance balance The instance variables are declared as private so that the information is hidden from other classes.

11 11 Definisi Class public class PhoneCard { // attributes private String phoneNumber; private double balance; //methods go here … } class in UML notation class in Java

12 12 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 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. Constructor with arguments which sets instance variables to the values of the arguments passed in.

13 13 Contoh – Default Constructor public class PhoneCard { // attributes private String phoneNumber; private double balance; // 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. constructor has the same name as the class, and no return type.

14 14 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

15 15 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.

16 16 Reader/accessor Methods (getters) public class PhoneCard { // 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 The return type is String This getter 'gets' the balance phone number returned the double value balance returned

17 17 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.

18 18 Writer Methods public class PhoneCard { // attributes private String phoneNumber; private double balance; //writer methods public 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.

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

20 20 Standard Methods We say that the Constructor, Constructor, Getter, Getter, Setter and Setter and Query Query methods are standard methods because we expect them to be available for most class providers.

21 21 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 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. record that calls have been made: to decrease the balance in the card. We have to write methods to carry out the above functions.

22 22 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; }

23 23 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.

24 24 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; // set to zero return false; } return true; }

25 25 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.

26 26 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

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

28 28 Latihan Now test your Rectangle class using a driver program. Create one rectangle using the no-args Constructor Create one rectangle using the no-args Constructor Create another rectangle using the arguments 5.5 for length and 7.8 for width. 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 Set the length and width of the first rectangle using the 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 area. Display information about the rectangle with the larger area.

29 29 The Circle class A Circle class provider has been defined: it can be used to create Circle objects. Test the Circle class: public Circle() 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.

30 30 Other Classes What data and methods would you define for the following objects? Bank Account Bank Account Student Student Library Book Library Book Car Car Write the class providers.


Download ppt "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."

Similar presentations


Ads by Google