820 likes | 837 Views
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?.
E N D
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? • 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)
PowerPoint File Edit … Help Creating new document Opening a document Saving a document … Exiting program An Example Of The Procedural Approach
Dungeon Master Broadsword Longbow Rapier An Example Of The Object-Oriented Approach Weapons Monsters Scorpion Dragon Mummy Ghost Armour : Screamer Knight
Example Objects: Monsters From Dungeon Master • Dragon • Scorpion • Couatl
Ways Of Describing A Monster What can the dragon do? What are the dragon’s attributes?
Monsters: Attributes • Represents information about the monster: • Name • Damage it inflicts • Damage it can sustain • Speed • :
Monsters: Operations • Represents what each monster can do (verb part): • Dragon • Scorpion Stinger
Wings Serpent (poison) Monsters: Operations • Couatl
18’ 25’ Pascal Records Vs. Java Objects Composite type (Records) • Information (attributes) • What the variable “knows”
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
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)
Illustrating The Need For Information Hiding: An Example • Creating a new monster: “The Critter” • Attribute: Height (must be 60” – 72”)
Illustrating The Need For Information Hiding: An Example • Creating a new monster: “The Critter” • Attribute: Height (must be 60” – 72”)
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
I) Defining A Java Class • Format of class definition: • class <name of class> • { • instance fields/attributes • instance methods • }
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”.
Defining A Java Class (3) • Example: • class Foo • { • private int num; • public void greet () • { • System.out.println(“Hello”); • } • }
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”.
References • It is a pointer that cannot be de-referenced by the programmer • Automatically garbage collected when no longer needed
var numPtr : ^ integer; begin new(numPtr); numPtr numPtr ^ De-Referencing Pointers: Pascal Example I
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);
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
Java References • It is a pointer that cannot be de-referenced by the programmer • Automatically garbage collected when no longer needed
numPtr numPtr ^ Garbage Collection And Pointers: Pascal Example
Garbage Collection And Pointers: Pascal Example dispose(numPtr); numPtr numPtr ^
Garbage Collection And Pointers: Pascal Example dispose(numPtr); numPtr := NIL; numPtr numPtr ^ NIL
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
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
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
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
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; }
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
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
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()); • } • }
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; • } • }
Foo -num: int -<attribute name>: <attribute type> <Name of class> +setNum () +getNum () +<method name> () UML1 Representation Of A Class UML = Unified Modeling Language
Common Errors When Using References • Forgetting to initialize the reference • Using a null reference
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);
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);
Encapsulation • Grouping data methods together within a class definition to allow the private attributes to be accessible only through the public methods.
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
Showing The Need For Information Hiding: An Example • class Driver • { • public static void main (String [] args) • { • Inventory chinookInventory = new Inventory (); • int menuSelection; • int amount;
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();
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;
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;
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); • } • }
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; • }
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); • } • }
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;