Week 8Classes & Objects:Writing Classes,Creating and UsingObjects
Copyright Warning                             COMMONWEALTH OF AUSTRALIA                               Copyright Regulation...
Classes & Objects?• Last time, we looked at the idea of classes to  group together data of different types about  somethin...
Why Classes & Objects?• Prime purpose: to group together data items  related to one thing• Also: we can include methods in...
Writing Classes• The programs we’ve written in previous examples  have used classes defined in the Java standard  class li...
Structure of A Class• A class can contain data declarations and method  declarations                int size, weight;     ...
Classes: State & Behaviour• The values of the attribute data define the state of  an object created from the class• The fu...
Designing the BankAccount Class• Lets go back to the BankAccount class from last  time. Here is what we designed so far:  ...
Constructors•    A constructor method is a special method that is    used to set up an object when it is initially created...
Constructors• Note that we can use the names of the attribute  variables• Thats because the constructor method makes a  ne...
Multiple Constructors            public BankAccount(int acct,                                                     int PinN...
Making An Object in Bluej• Compile, and right-click on the class file• Choose one of the constructor methods• Fill in the ...
Inspecting An Object in Bluej• Right-click on the object, and choose Inspect• Bluej shows you the values of the attributes...
The toString() Method• We need to add more methods to the class, to  make it useful• All classes that represent objects sh...
toString() for BankAccount  public String toString()  {    return(“Account “ + accountNumber +             “, $” + balance...
Gettor or Accessor Methods• Accessor methods allow external access to the  objects attributes• They also protect the objec...
Settor or Mutator Methods• Settor methods allow the objects attributes to be  set or updated• Again, they also protect the...
Instance Data• The balance variable in the BankAccount class is  called instance data because each instance  (object) that...
Scope and Local Variables• The scope of a variable is the area in a program in  which that variable can be referenced (use...
Encapsulation• We can take one of two views of an object:        internal - the details of the variables and methods of t...
Encapsulation• One object (called the client) may use another  object for the services it provides• The client of an objec...
Encapsulation• An encapsulated object can be thought of as a  black box -- its inner workings are hidden from the  client•...
Visibility Modifiers• In Java, we accomplish encapsulation through the  appropriate use of visibility modifiers• A modifie...
Visibility Modifiers• Public variables violate encapsulation because  they allow the client to “reach in” and modify the  ...
Visibility Modifiers• Methods that provide the objects services are  declared with public visibility so that they can be  ...
Visibility Modifiers                                            public     private                                       V...
Accessors and Mutators• Because instance data is private, a class usually  provides services to access and modify data  va...
Mutator Restrictions• The use of mutators gives the class designer the  ability to restrict a client’s options to modify a...
Methods Calling Method• Methods in your class are normal Java methods  like we have seen before• They can have their own v...
Method Control Flow• If the called method is in the same class, only the  method name is needed                           ...
Method Control Flow• The called method is often part of another class or  object                     main                 ...
Using Objects in Java• We have shown you how to create objects with  Bluej• This is only for testing. Normally, you would ...
Constructing Objects in Java• Use the new command to construct an object;  provide a set of parameters that will match one...
Using Objects in Java• Once an object is constructed, we can use any of  the methods from the class, via the object.      ...
The static Keyword• A static method is a special method that does     not require an object to invoke• It is used when a m...
Classes: Not Just Real Things• Classes are just to group related data together,  and to provide a set of methods to correc...
Strings are Objects• Strings in Java are objects, and there is a String  class that provides a useful set of methods to  m...
Useful String Methods• See the on-line String class documentation for  more details           charAt() - Get a char at a ...
The Last Slide!• Types that start with lowercase in Java are  primitive types, not classes/objects        byte, short, in...
Upcoming SlideShare
Loading in …5
×

Week08

444 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
444
On SlideShare
0
From Embeds
0
Number of Embeds
212
Actions
Shares
0
Downloads
7
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Week08

  1. 1. Week 8Classes & Objects:Writing Classes,Creating and UsingObjects
  2. 2. Copyright Warning COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been copied and communicated to you by or on behalf of Bond University pursuant to Part VB of the Copyright Act 1968 (the Act).The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under the Act.Do not remove this notice.© 2004 Pearson Addison-Wesley. All rights reserved 4-2
  3. 3. Classes & Objects?• Last time, we looked at the idea of classes to group together data of different types about something• A Java class provides a template for the things in the class, e.g. all bank accounts• An object, built from the class template, represents a single thing, i.e. one account• Each object in the class will have the same set of attributes, but each object can have different values for the attributes© 2004 Pearson Addison-Wesley. All rights reserved 4-3
  4. 4. Why Classes & Objects?• Prime purpose: to group together data items related to one thing• Also: we can include methods in the class, so that the data items can be manipulated in a consistent way• Also: we can protect the data items, so that the only access to them is through the methods provided• This ensures that, despite bugs or malicious code, our data remains intact and useful  e.g. what if someone tried to withdraw money from a bank account without knowing the PIN?© 2004 Pearson Addison-Wesley. All rights reserved 4-4
  5. 5. Writing Classes• The programs we’ve written in previous examples have used classes defined in the Java standard class library• Now we will begin to design programs that rely on classes that we write ourselves• The class that contains the main() method is just the starting point of a program• True object-oriented programming is based on defining classes that represent objects with well- defined characteristics and functionality© 2004 Pearson Addison-Wesley. All rights reserved 4-5
  6. 6. Structure of A Class• A class can contain data declarations and method declarations int size, weight; Data declarations char category; Method declarations© 2004 Pearson Addison-Wesley. All rights reserved 4-6
  7. 7. Classes: State & Behaviour• The values of the attribute data define the state of an object created from the class• The functionality of the methods define the behaviors of the object• Given a class, we can create or construct an object from the class, with its own state• Then, the object uses its own methods to manipulate its attributes© 2004 Pearson Addison-Wesley. All rights reserved 4-7
  8. 8. Designing the BankAccount Class• Lets go back to the BankAccount class from last time. Here is what we designed so far: public class BankAccount { int accountNumber; double balance; int PinNumber; }• These are the attributes, or the state, that each object constructed from the class will have.• The first method we need to write is a constructor method.© 2004 Pearson Addison-Wesley. All rights reserved 4-8
  9. 9. Constructors• A constructor method is a special method that is used to set up an object when it is initially created from the class template• A constructor has the same name as the class• It normally takes as inputs the values that will be put into the objects attributes public BankAccount(int acct, double bal, int pin) { accountNumber= acct; balance= bal; PinNumber= pin; }© 2004 Pearson Addison-Wesley. All rights reserved 4-9
  10. 10. Constructors• Note that we can use the names of the attribute variables• Thats because the constructor method makes a new object, and each object has its own attribute variables• Scope rule: if a variable isnt declared in a method, look for it as an attribute variable in the class• We can write several different constructors, as long as the list of input parameters is different for each one.• Lets write a constructor where no balance is given. What should the balance be set to?© 2004 Pearson Addison-Wesley. All rights reserved 4-10
  11. 11. Multiple Constructors public BankAccount(int acct, int PinNumber) { accountNumber= acct; balance= 0.0; this.PinNumber= PinNumber; }• We set the balance to 0.0, thus keeping the objects attributes safe and useful• Note: conflict between the input parameters name and the name of the attribute• To resolve this: we use this. to specify the attribute in this object© 2004 Pearson Addison-Wesley. All rights reserved 4-11
  12. 12. Making An Object in Bluej• Compile, and right-click on the class file• Choose one of the constructor methods• Fill in the input parameters & click Ok• The object appears down the bottom© 2004 Pearson Addison-Wesley. All rights reserved 4-12
  13. 13. Inspecting An Object in Bluej• Right-click on the object, and choose Inspect• Bluej shows you the values of the attributes• This creating/inspecting is only useful when testing the classes that you write© 2004 Pearson Addison-Wesley. All rights reserved 4-13
  14. 14. The toString() Method• We need to add more methods to the class, to make it useful• All classes that represent objects should define a toString() method: Java expects this• The toString() method returns a String that represents the object in some way• It is called automatically when an object is concatenated to a string or when it is passed to the println() method• Its up to you, the designer, to think of how to best represent the objects attributes as a string© 2004 Pearson Addison-Wesley. All rights reserved 4-14
  15. 15. toString() for BankAccount public String toString() { return(“Account “ + accountNumber + “, $” + balance); }• Once you have constructed an object with Bluej, you can right-click on it, and run any of its methods© 2004 Pearson Addison-Wesley. All rights reserved 4-15
  16. 16. Gettor or Accessor Methods• Accessor methods allow external access to the objects attributes• They also protect the object from unauthorised use• For the BankAccount class:  int getAccountNumber()  int getBalance(int pin)  no method to get the PIN: user should know it• Note that getBalance() requires knowledge of the PIN: an example of the method protecting the data kept inside the object• Again, once an object is created, Bluej allows you to run any of its methods on itself© 2004 Pearson Addison-Wesley. All rights reserved 4-16
  17. 17. Settor or Mutator Methods• Settor methods allow the objects attributes to be set or updated• Again, they also protect the object from being corrupted• For the BankAccount class:  boolean deposit(double amount)  boolean withdraw(int pin, double amount)  boolean setPIN(int oldpin, int newpin)• Anybody can deposit money, only people with the PIN can withdraw or set a new PIN• All methods in this example return true if the operation succeeded.• Note: all methods check their input values!• 2004 Pearson Addison-Wesley. All rights reserved© Note the strict requirements for withdraw() 4-17
  18. 18. Instance Data• The balance variable in the BankAccount class is called instance data because each instance (object) that is created has its own version of it• A class declares the type of the data, but it does not reserve any memory space for the variables• Every time a BankAccount object is created, a new balance variable is created as well• The objects of a class share the methods in the class, but each object has its own instance variables• Thats the only way two objects can have different states© 2004 Pearson Addison-Wesley. All rights reserved 4-18
  19. 19. Scope and Local Variables• The scope of a variable is the area in a program in which that variable can be referenced (used)• Variables declared at the class level can be referenced by all methods in that class• Variables declared within a method can be used only in that method• Variables declared within a method are called local variables• In the BankAccount class, the variable interest is declared inside the calculateInterest() method - it is local to that method and cannot be referenced anywhere else© 2004 Pearson Addison-Wesley. All rights reserved 4-19
  20. 20. Encapsulation• We can take one of two views of an object:  internal - the details of the variables and methods of the class that defines it  external - the services that an object provides and how the object interacts with the rest of the system• From the external view, an object is an encapsulated entity, providing a set of specific services  accessor methods, settor methods etc.• These services define the interface to the object© 2004 Pearson Addison-Wesley. All rights reserved 4-20
  21. 21. Encapsulation• One object (called the client) may use another object for the services it provides• The client of an object may request its services (call its methods), but it should not have to be aware of how those services are accomplished• Any changes to the objects state (its variables) should be made by that objects methods• We should make it difficult, if not impossible, for a client to access an object’s variables directly• That is, an object should be self-governing© 2004 Pearson Addison-Wesley. All rights reserved 4-21
  22. 22. Encapsulation• An encapsulated object can be thought of as a black box -- its inner workings are hidden from the client• The client invokes the interface methods of the object, which manages the instance data Client Methods Data© 2004 Pearson Addison-Wesley. All rights reserved 4-22
  23. 23. Visibility Modifiers• In Java, we accomplish encapsulation through the appropriate use of visibility modifiers• A modifier is a Java reserved word that specifies particular characteristics of a method or data• Members of a class that are declared with public visibility can be referenced anywhere• Members of a class that are declared with private visibility can be referenced only by the methods within that class© 2004 Pearson Addison-Wesley. All rights reserved 4-23
  24. 24. Visibility Modifiers• Public variables violate encapsulation because they allow the client to “reach in” and modify the values directly; this is usually very bad• Therefore instance variables should not be declared with public visibility• It is acceptable to give a constant public visibility, which allows it to be used outside of the class• Public constants do not violate encapsulation because, although the client can access it, its value cannot be changed© 2004 Pearson Addison-Wesley. All rights reserved 4-24
  25. 25. Visibility Modifiers• Methods that provide the objects services are declared with public visibility so that they can be invoked by clients• Public methods are also called service methods• A method created simply to assist a service method is called a support method• Since a support method is not intended to be called by a client, it should not be declared with public visibility© 2004 Pearson Addison-Wesley. All rights reserved 4-25
  26. 26. Visibility Modifiers public private Violate Enforce Variables encapsulation encapsulation Support other Provide services Methods methods in the to clients class© 2004 Pearson Addison-Wesley. All rights reserved 4-26
  27. 27. Accessors and Mutators• Because instance data is private, a class usually provides services to access and modify data values• An accessor method returns the current value of a variable• A mutator method changes the value of a variable• The names of accessor and mutator methods take the form getX and setX, respectively, where X is the name of the value• They are sometimes called “gettors” and “settors”© 2004 Pearson Addison-Wesley. All rights reserved 4-27
  28. 28. Mutator Restrictions• The use of mutators gives the class designer the ability to restrict a client’s options to modify an object’s state• A mutator is often designed so that the values of variables can be set only within particular limits• For example, the setFaceValue mutator of the Die class should have restricted the value to the valid range (1 to MAX)• We’ll see in Chapter 5 how such restrictions can be implemented© 2004 Pearson Addison-Wesley. All rights reserved 4-28
  29. 29. Methods Calling Method• Methods in your class are normal Java methods like we have seen before• They can have their own variables, and have normal Java control structures• Methods can call other methods• If the other method is in the same class, we can simply use its name• If the other method is in a different class, or is a method inside an object, we have to write the name of the class/object, dot, then the method name© 2004 Pearson Addison-Wesley. All rights reserved 4-29
  30. 30. Method Control Flow• If the called method is in the same class, only the method name is needed compute myMethod myMethod();© 2004 Pearson Addison-Wesley. All rights reserved 4-30
  31. 31. Method Control Flow• The called method is often part of another class or object main doIt helpMe obj.doIt(); helpMe();© 2004 Pearson Addison-Wesley. All rights reserved 4-31
  32. 32. Using Objects in Java• We have shown you how to create objects with Bluej• This is only for testing. Normally, you would write a client program that uses a class to create objects from that class• For example, the MyBank program is an example of a program that makes and uses BankAccount objects• WARNING!!! When you declare BankAccount userAcct; this DOES NOT create an object!• It only declares the name of an object in the future• You must still construct an object for it to be created© 2004 Pearson Addison-Wesley. All rights reserved 4-32
  33. 33. Constructing Objects in Java• Use the new command to construct an object; provide a set of parameters that will match one of the constructor methods, e.g computerAcct= new BankAccount(6475, 1123);• Java runs the constructor, and a new object is stored in the computers memory.• It doesnt appear in the Bluej window.• To see it, use the debugger to inspect the computerAcct variable• You can pass any parameters to a constructor: literal constants, variables holding values passed in by the user etc.© 2004 Pearson Addison-Wesley. All rights reserved 4-33
  34. 34. Using Objects in Java• Once an object is constructed, we can use any of the methods from the class, via the object. objects name.method(parameters);• For example: userAccount.calculateInterest(0.08);• In fact, you have been constructing and using objects already: Scanner scan = new Scanner(System.in); question= scan.nextLine();© 2004 Pearson Addison-Wesley. All rights reserved 4-34
  35. 35. The static Keyword• A static method is a special method that does not require an object to invoke• It is used when a method is not specific to any object• A static method is invoked through the name of the class rather than the name of an object of that class• For example, Math.max(int, int) returns the value of the larger of two integer arguments• Examples of use: big = Math.max(a, b); System.out.println( big );• All of your main() programs have been static, so you could run them without objects© 2004 Pearson Addison-Wesley. All rights reserved 4-35
  36. 36. Classes: Not Just Real Things• Classes are just to group related data together, and to provide a set of methods to correctly manipulate that data• A Class, and its objects, dont have to represent real things; just a group of related data• Each pixel on a screen has a <red,green,blue> colour, and possibly a transparency percentage public class Pixel { byte red,green,blue; byte transparency; }© 2004 Pearson Addison-Wesley. All rights reserved 4-36
  37. 37. Strings are Objects• Strings in Java are objects, and there is a String class that provides a useful set of methods to manipulate Strings• Each string literal (enclosed in double quotes) represents a String object• Once a String object has been created, neither its value nor its length can be changed• However, several methods of the String class return new String objects that are modified versions of the original© 2004 Pearson Addison-Wesley. All rights reserved 4-37
  38. 38. Useful String Methods• See the on-line String class documentation for more details  charAt() - Get a char at a particular position  compareTo() - Compare a string to another one  endsWith() - See if a string ends with a suffix  indexOf() - Find first position of a char in string  length() - Returns the strings length  replace() - Replaces all of ch1 with ch2 in string  trim() - Remove leading/trailing whitespace© 2004 Pearson Addison-Wesley. All rights reserved 4-38
  39. 39. The Last Slide!• Types that start with lowercase in Java are primitive types, not classes/objects  byte, short, int, long, char, float, double, boolean• Any type that starts with an uppercase letter is a class, and you must construct objects from the class, and use class methods• The String class is one exception, you can do String message = “This is a message”;• Just as we can have arrays or primitive types, we can also have arrays of objects. To use the method of one object in the array, we dobankaccountList[8].withdraw(1234, 75.00); array name index method© 2004 Pearson Addison-Wesley. All rights reserved 4-39

×