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.

Slides:



Advertisements
Similar presentations
UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1.
Advertisements

CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
1 Classes and Objects in Java Basics of Classes in Java.
Final and Abstract Classes
Basic Java Constructs and Data Types – Nuts and Bolts
1 Inheritance Classes and Subclasses Or Extending a Class.
Classes and Objects in Java
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Chapter 14 Inheritance. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Inheritance Basics Derived classes, with.
Chapter 4 Parameters and Overloading. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Learning Objectives Parameters Call-by-value Call-by-reference.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 1 The Study of Body Function Image PowerPoint
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 11: Structure and Union Types Problem Solving & Program Design.
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
My Alphabet Book abcdefghijklm nopqrstuvwxyz.
FACTORING ax2 + bx + c Think “unfoil” Work down, Show all steps.
4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.
Lecture 15 Linked Lists part 2
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
Data Structures ADT List
Chapter 24 Lists, Stacks, and Queues
1 Linked Lists III Template Chapter 3. 2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.
ABC Technology Project
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Classes and Objects CMSC 202. Version 9/122 Programming & Abstraction All programming languages provide some form of abstraction. – Also called information.
Understanding class definitions Looking inside classes 5.0.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 12 – Security Panel Application Introducing.
VOORBLAD.
21-Aug-14 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
© 2012 National Heart Foundation of Australia. Slide 2.
1 Review Quisioner Kendala: Kurang paham materi. Praktikum Pengaruh teman.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Understanding Generalist Practice, 5e, Kirst-Ashman/Hull
1 Variables and Data Types. 2 Variable Definition a location in memory, referenced by a name (identifier), where data of a given type can be stored, changed,
Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by.
25 seconds left…...
Equal or Not. Equal or Not
Januar MDMDFSSMDMDFSSS
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 10 – Enhancing the Wage Calculator Application:
We will resume in: 25 Minutes.
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
PSSA Preparation.
CHAPTER 11 FILE INPUT & OUTPUT Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
Chapter 13 – Introduction to Classes
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Topics Instance variables, set and get methods Encapsulation
Class Definitions: The Fundamentals Chapter 6 3/30/15 & 4/2/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education.
Defining Classes and Methods
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Presentation transcript:

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 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 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 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 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 Bagaimana objects dibuat PhoneCard myCard = new PhoneCard(" ", 20); The constructor call creates a new object: myCard

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 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 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 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 Definisi Class public class PhoneCard { // attributes private String phoneNumber; private double balance; //methods go here … } class in UML notation class in Java

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