1 / 82

CPSC 233: Introduction to Classes and Objects, Part I

CPSC 233: Introduction to Classes and Objects, Part I. Attributes and methods Creating new classes References: Dynamic memory allocation and automatic garbage collection Encapsulation and information hiding Constructors Shadowing Arrays. What Does Object-Oriented Mean?.

edwinaa
Download Presentation

CPSC 233: Introduction to Classes and Objects, Part I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CPSC 233: Introduction to Classes and Objects, Part I Attributes and methods Creating new classes References: Dynamic memory allocation and automatic garbage collection Encapsulation and information hiding Constructors Shadowing Arrays

  2. What Does Object-Oriented Mean? • Procedural approach (CPSC 231) • Design and build the software in terms of actions (verbs) • Object-Oriented approach (CPSC 233) • Design and build the software in terms of things (nouns)

  3. PowerPoint File Edit … Help Creating new document Opening a document Saving a document … Exiting program An Example Of The Procedural Approach

  4. Dungeon Master Broadsword Longbow Rapier An Example Of The Object-Oriented Approach Weapons Monsters Scorpion Dragon Mummy Ghost Armour : Screamer Knight

  5. Example Objects: Monsters From Dungeon Master • Dragon • Scorpion • Couatl

  6. Ways Of Describing A Monster What can the dragon do? What are the dragon’s attributes?

  7. Monsters: Attributes • Represents information about the monster: • Name • Damage it inflicts • Damage it can sustain • Speed • :

  8. Monsters: Operations • Represents what each monster can do (verb part): • Dragon • Scorpion Stinger

  9. Wings Serpent (poison) Monsters: Operations • Couatl

  10. 18’ 25’ Pascal Records Vs. Java Objects Composite type (Records) • Information (attributes) • What the variable “knows”

  11. 18’ 25’ Pascal Records Vs. Java Objects Composite type (Objects) • Information (attributes) • What the variable “knows” • Operations (methods1) • What the variable “can do” 1 A method is anothername for a procedure or function in Java

  12. Information Hiding • An important part of Object-Oriented programming • Protects the inner-workings (data) of a class • Only allow access to the core of an object in a controlled fashion (use the public parts to access the private sections)

  13. Illustrating The Need For Information Hiding: An Example • Creating a new monster: “The Critter” • Attribute: Height (must be 60” – 72”)

  14. Illustrating The Need For Information Hiding: An Example • Creating a new monster: “The Critter” • Attribute: Height (must be 60” – 72”)

  15. Working With Objects In Java • I) Define the class • II) Create an instance of the class (instantiate an object) • III) Using different parts of an object

  16. I) Defining A Java Class • Format of class definition: • class <name of class> • { • instance fields/attributes • instance methods • }

  17. Defining A Java Class (2) • Format of instance fields: • <access modifier>1 <type of the field> <name of the field>; • Format of instance methods: • <access modifier>1 <return type2> <method name> (<p1 type> <p1 name>…) • { • <Body of the method> • } 1) Can be public or private but typically instance fields are private while instance methods are public 2) Valid return types include the simple types (e.g., int, char etc.), predefined classes (e.g., String) or new classes that you have defined in your program. A method that returns nothing has return type of “void”.

  18. Defining A Java Class (3) • Example: • class Foo • { • private int num; • public void greet () • { • System.out.println(“Hello”); • } • }

  19. II) Creating Instances Of A Class • Format: • <class name><instance name> = new <class name> (); • Example: • Foo f = new Foo (); • Note: “f” is not an object of type “Foo” but a reference to an object of type “Foo”.

  20. References • It is a pointer that cannot be de-referenced by the programmer • Automatically garbage collected when no longer needed

  21. var numPtr : ^ integer; begin new(numPtr); numPtr numPtr ^ De-Referencing Pointers: Pascal Example I

  22. De-Referencing Pointers: Pascal Example II • type • Client = record • firstName : array [1..24] of char; • lastName : array [1..24] of char; • income : real; • email : array [1..50] of char; • end; (* Declaration of record Client *) • NodePointer = ^ Node; • Node = record • data : Client; • nextPointer : NodePointer; • end; (* Declaration of record Node *) • : : • : : • writeln('First name: ':20, currentNode^.data.firstName);

  23. III) Using The Parts Of A Class • Format: • <instance name>.<attribute name>; • <instance name>.<method name>; • Example: • Foo f = new Foo (); • f.greet(); Note: In order to use the dot-operator “.” the instance field or method cannot have a private level of access

  24. Java References • It is a pointer that cannot be de-referenced by the programmer • Automatically garbage collected when no longer needed

  25. numPtr numPtr ^ Garbage Collection And Pointers: Pascal Example

  26. Garbage Collection And Pointers: Pascal Example dispose(numPtr); numPtr numPtr ^

  27. Garbage Collection And Pointers: Pascal Example dispose(numPtr); numPtr := NIL; numPtr numPtr ^ NIL

  28. Object (A “Foo”) Object (A “Foo”) Automatic Garbage Collection Of Java References • Dynamically allocated memory is automatically freed up when it is no longer referenced References Dynamic memory f1 f2

  29. Object (A “Foo”) Object (A “Foo”) Automatic Garbage Collection Of Java References (2) • Dynamically allocated memory is automatically freed up when it is no longer referenced e.g., f2 = null; References Dynamic memory f1 f2 null

  30. Object (A “Foo”) Object (A “Foo”) Automatic Garbage Collection Of Java References (2) • Dynamically allocated memory is automatically freed up when it is no longer referenced e.g., f2 = null; References Dynamic memory f1 f2 null

  31. publicmethod publicmethod publicmethod private data Public And Private Parts Of A Class • The public methods can be used do things such as access or change the instance fields of the class get data set data

  32. Public And Private Parts Of A Class (2) • Types of methods that utilize the instance fields: • Accessor methods “get” • Used to determine the current value of a field • Example: public int getNum () { return num; } • Mutator methods “set” • Used to set a field to a new value • Example: public void setNum (int n) { num = n; }

  33. The program must contain a “driver” class The driver class is the place where the program starts running (contains the one, and only one, main method) Instances of other classes can be created here Java program Driver main () { } Foo f = new Foo (); Laying Out Your Program Foo

  34. Points To Keep In Mind About The Driver Class • Contains the only main method of the whole program (where execution begins) • Do not instantiate instances of the Driver1 • For now avoid: • Defining instance fields / attributes for the Driver1 • Defining methods for the Driver (other than the main method)1 1 Details will be provided later in this course

  35. Putting It Altogether: First Object-Oriented Example • Example (The complete example can be found in the directory /home/233/examples/classes_objects/firstExample • class Driver • { • public static void main (String [] args) • { • Foo f = new Foo (); • f.setNum(10); • System.out.println("Current value of num = " + f.getNum()); • } • }

  36. Putting It Altogether: First Object-Oriented Example (2) • class Foo • { • private int num; • public void setNum (int n) • { • num = n; • } • public int getNum () • { • return num; • } • }

  37. Foo -num: int -<attribute name>: <attribute type> <Name of class> +setNum () +getNum () +<method name> () UML1 Representation Of A Class UML = Unified Modeling Language

  38. Common Errors When Using References • Forgetting to initialize the reference • Using a null reference

  39. Compilation error! > javac Driver.java Driver.java:14: variable f might not have been initialized f.setNum(10); ^ 1 error Error: Forgetting To Initialize The Reference • Foo f; • f.setNum(10);

  40. Run-time error! > java Driver Exception in thread "main" java.lang.NullPointerException at Driver.main(Driver.java:14) Error: Using Null References • Foo f = null; • f.setNum(10);

  41. Encapsulation • Grouping data methods together within a class definition to allow the private attributes to be accessible only through the public methods.

  42. How Does Hiding Information Protect The Class? • Protects the inner-workings (data) of a class • e.g., range checking for inventory levels (0 – 100) • The complete example can be found in the directory /home/233/examples/classes_objects/secondExample

  43. Showing The Need For Information Hiding: An Example • class Driver • { • public static void main (String [] args) • { • Inventory chinookInventory = new Inventory (); • int menuSelection; • int amount;

  44. Showing The Need For Information Hiding: An Example (2) • do • { • System.out.println("\n\nINVENTORY PROGRAM: OPTIONS"); • System.out.println("\t(1)Add new stock to inventory"); • System.out.println("\t(2)Remove stock from inventory"); • System.out.println("\t(3)Display stock level"); • System.out.println("\t(4)Check if stock level is critically low"); • System.out.println("\t(5)Quit program"); • System.out.print("Selection: "); • menuSelection = Console.in.readInt(); • Console.in.readChar(); • System.out.println();

  45. Showing The Need For Information Hiding: An Example (3) • switch (menuSelection) • { • case 1: • System.out.print("No. items to add: "); • amount = Console.in.readInt(); • Console.in.readChar(); • chinookInventory.stockLevel = chinookInventory.stockLevel • + amount; • System.out.println(chinookInventory.getInventoryLevel()); • break; • case 2: • System.out.print("No. items to remove: "); • amount = Console.in.readInt(); • Console.in.readChar(); • chinookInventory.stockLevel = chinookInventory.stockLevel • - amount; • System.out.println(chinookInventory.getInventoryLevel()); • break;

  46. Showing The Need For Information Hiding: An Example (4) • case 3: • System.out.println(chinookInventory.getInventoryLevel()); • break; • case 4: • if (chinookInventory.inventoryTooLow()) • System.out.println("Stock levels critical!"); • else • System.out.println("Stock levels okay"); • System.out.println(chinookInventory.getInventoryLevel()); • break; • case 5: • System.out.println("Quitting program"); • break;

  47. Showing The Need For Information Hiding: An Example (5) • default: • System.out.println("Enter one of 1, 2, 3, 4 or 5"); • } • } while (menuSelection != 5); • } • }

  48. Showing The Need For Information Hiding: An Example (6) • class Inventory • { • public int stockLevel; • public void addToInventory (int amount) • { • stockLevel = stockLevel + amount; • } • public void removeFromInventory (int amount) • { • stockLevel = stockLevel - amount; • }

  49. Showing The Need For Information Hiding: An Example (7) • public boolean inventoryTooLow () • { • final int CRITICAL = 10; • if (stockLevel < CRITICAL) • return true; • else • return false; • } • public String getInventoryLevel () • { • return("No. items in stock: " + stockLevel); • } • }

  50. Utilizing Information Hiding: An Example • The complete example can be found in the directory /home/233/examples/classes_objects/thirdExample • class Driver • { • public static void main (String [] args) • { • Inventory chinookInventory = new Inventory (); • int menuSelection; • int amount;

More Related