ObjectOriented Principles in Java Part I Encapsulation Information
Object-Oriented Principles in Java: Part I Encapsulation Information Hiding Implementation Hiding Creating Objects in Java Class attributes vs. instance attributes Object-Oriented Principles in Java: Part I James Tam
What Does Object-Oriented Mean? Procedural approach (CPSC 231) • Design and build the software in terms of actions (verbs) Object-Oriented approach (most of CPSC 233) • Design and build the software in terms of things (nouns) Object-Oriented Principles in Java: Part I James Tam
An Example Of The Procedural Approach Power. Point File Creating new document Edit Opening a document Object-Oriented Principles in Java: Part I … Saving a document Help … Exiting program James Tam
An Example Of The Object-Oriented Approach Dungeon Master Weapons Monsters Broadsword Scorpion Longbow Dragon Mummy Ghost Screamer Object-Oriented Principles in Java: Part I Knight Rapier Armour : James Tam
Characteristics Of The Object-Oriented Approach Two are covered in this section of notes: • Encapsulation • Hiding (information / implementation) Object-Oriented Principles in Java: Part I James Tam
Characteristics Of The Object-Oriented Approach Two are covered in this section of notes: • Encapsulation • Hiding (information / implementation) Object-Oriented Principles in Java: Part I James Tam
Encapsulation “Grouping together under a name” You’ve already done this in CPSC 231: • Problem decomposition: Procedures and functions in A 5: Checkers • Composite types: Records for A 6 & A 7: Movie list Object-Oriented Principles in Java: Part I James Tam
Encapsulation Through Procedures And Functions An example: Displaying the checker board Object-Oriented Principles in Java: Part I James Tam
Encapsulation Through Procedures And Functions An example: Displaying the checker board writeln('1 2 3 4 5 6 7 8 ': 19); for r : = 1 to BOARDSIZE do begin writeln('- - - - ': 19); write(r: 2, '|'); for c : = 1 to BOARDSIZE do begin write(checker. Board[r][c], '|'); end; writeln('- - - - ': 19); end Object-Oriented Principles in Java: Part I James Tam
Encapsulation Through Procedures And Functions An example: Displaying the checker board display. Board(checker. Board); procedure display. Board (checker. Board : Board); begin for r : = 1 to BOARDSIZE do for c : = 1 to BOARDSIZE do write(checker. Board[r][c]); end; Object-Oriented Principles in Java: Part I James Tam
The Need For Encapsulation With Records Each movie is described with several attributes: • Movie name: array [1. . 80] of char; • Cast: array [1. . 5, 1. . 80] of char; • Genre: array [1. . 80] of char; • Rating: array [1. . 5] of char; • Number of stars: integer; • Director: array [1. . 80] of char; • Format: • • DVD: boolean; VHS: boolean; proc (name, cast, genre, rating, stars, director, dvd, vhs); Object-Oriented Principles in Java: Part I James Tam
Encapsulation With Records Each movie is described with several attributes: Movie = record name : array [1. . 80] of char; cast : array [1. . 80] of char; genre : array [1. . 80] of char; rating : array [1. . 5] of char; stars : integer; director : array [1. . 80] of char; dvd : boolean; vhs : boolean; end; proc(movie. Variable); Object-Oriented Principles in Java: Part I James Tam
Encapsulation With The Procedural Approach (Pascal Records) Composite type (Records) Attributes (data) • What the variable “knows” Object-Oriented Principles in Java: Part I James Tam
Encapsulation With The Object-Oriented Approach (Java Classes) Composite type (Objects) Attributes (data) • What the variable “knows” Operations (methods 1) • What the variable “can do” 1 A method is the name for a procedure or function in Java Object-Oriented Principles in Java: Part I James Tam
Example Objects: Monsters From Dungeon Master Dragon • Scorpion • Couatl Object-Oriented Principles in Java: Part I James Tam
Monsters: Attributes Represents information (may be common to all or unique to some): • Name • Speed • Damage it inflicts • Damage it can sustain : Object-Oriented Principles in Java: Part I James Tam
Monsters: Operations Represents what each monster can do Often unique to a type of monster Example Dragon Scorpion Stinger Object-Oriented Principles in Java: Part I James Tam
Monsters: Operations Couatl Wings Serpent (poison) Object-Oriented Principles in Java: Part I James Tam
Working With Objects In Java Define the class Declare an instance of the class (instantiate an object) Accessing different parts of an object Object-Oriented Principles in Java: Part I James Tam
Defining A Java Class Format: class <name of class> { fields methods } Example: class Foo { int num; void display. Num () { System. out. println(num); } } Object-Oriented Principles in Java: Part I James Tam
Instantiating Instances Of A Class Format: <Class name> <instance name> = new <Class name> (); Example: Foo f = new Foo (); Object-Oriented Principles in Java: Part I James Tam
Accessing Parts Of A Class Format: <instance name>. <attribute name>; <instance name>. <method name>; Example: Foo f = new Foo (); Object-Oriented Principles in Java: Part I James Tam
The Basics Of Classes: An Example (The complete example can be found in the directory /home/profs/tamj/233/examples/inventory. Class/version 1): class Inventory { final int CRITICAL = 10; int stock. Level; void add. To. Inventory (int amount) { stock. Level = stock. Level + amount; } void remove. From. Inventory (int amount) { stock. Level = stock. Level - amount; } Object-Oriented Principles in Java: Part I James Tam
The Basics Of Classes: An Example (2) boolean inventory. Too. Low () { if (stock. Level < CRITICAL) return true; else return false; } void display. Inventory. Level () { System. out. println("No. items in stock: " + stock. Level); } } Object-Oriented Principles in Java: Part I James Tam
The Basics Of Classes: An Example (3) import tio. *; class Driver { public static void main (String [] argv) { Inventory chinook. Inventory = new Inventory (); char menu. Option; int amount; boolean temp; do { System. out. println("nn. INVENTORY PROGRAM: OPTIONS"); System. out. println("t(A)dd new stock to inventory"); System. out. println("t(R)emove stock from inventory"); System. out. println("t(D)isplay stock level"); System. out. println("t(C)heck if stock level is critical"); System. out. print("t(Q)uit program"); System. out. println(); Object-Oriented Principles in Java: Part I James Tam
The Basics Of Classes: An Example (4) System. out. print("Selection: "); menu. Option = (char) Console. in. read. Char(); System. out. println(); switch (menu. Option) { case 'A': System. out. print("No. items to add: "); amount = Console. in. read. Int(); Console. in. read. Char(); chinook. Inventory. add. To. Inventory(amount); chinook. Inventory. display. Inventory. Level(); break; Object-Oriented Principles in Java: Part I James Tam
The Basics Of Classes: An Example (5) case 'R': System. out. print("No. items to remove: "); amount = Console. in. read. Int(); Console. in. read. Char(); chinook. Inventory. remove. From. Inventory(amount); chinook. Inventory. display. Inventory. Level(); break; case 'D': chinook. Inventory. display. Inventory. Level(); break; Object-Oriented Principles in Java: Part I James Tam
The Basics Of Classes: An Example (6) case 'C': temp = chinook. Inventory. inventory. Too. Low(); if (chinook. Inventory. inventory. Too. Low()) System. out. println("Stock levels critical!"); else System. out. println("Stock levels okay"); chinook. Inventory. display. Inventory. Level(); break; case 'Q': System. out. println("Quitting program"); break; default: System. out. println("Enter one of A, R, D, C or Q"); } } while (menu. Option != 'Q'); } } Object-Oriented Principles in Java: Part I James Tam
Characteristics Of The Object-Oriented Approach Two are covered in this section of notes: • Encapsulation • Hiding (information / implementation) Object-Oriented Principles in Java: Part I James Tam
Information Hiding Protects the inner-workings (data) of a class Only allow access to the core of an object in a controlled fashion Object-Oriented Principles in Java: Part I James Tam
Information Hiding (2) In Java use the keyword private for data Private parts of a class can only be accessed through the methods of that class Format: private <attribute type> <attribute name>; Example: private int num; Rule of thumb: • Unless there is a compelling reason, the data for a class should be hidden (private) Object-Oriented Principles in Java: Part I James Tam
Accessing Hidden Information In Java you can use the keyword public for methods The public parts of a class can be accessed anywhere in the program (used to access the private parts) method data Format: public <method return type> <method name> (<parameters>) Object-Oriented Principles in Java: Part I James Tam
Accessing Hidden Information (2) Example: public void add. To. Inventory (int amount) { stock. Level = amount; } Object-Oriented Principles in Java: Part I James Tam
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 directory: /home/profs/tamj/233/examples/inventory. Class/version 2 Object-Oriented Principles in Java: Part I James Tam
How Does Hiding Information Protect The Class? class Inventory { private final static int CRITICAL = 10; private final static int MIN = 0; private final static int MAX = 100; private int stock. Level; Object-Oriented Principles in Java: Part I James Tam
How Does Hiding Information Protect The Class? (2) public void add. To. Inventory (int amount) { int temp; temp = stock. Level + amount; if (temp > MAX) { System. out. print("Adding " + amount + " item will cause stock "); System. out. println("to become greater than " + MAX + " units"); } else { stock. Level = stock. Level + amount; } } Object-Oriented Principles in Java: Part I James Tam
How Does Hiding Information Protect The Class? (3) public void remove. From. Inventory (int amount) { int temp; temp = stock. Level - amount; if (temp < MIN) { System. out. println(); System. out. print("Removing " + amount + " item will cause stock "); System. out. println("to become less than " + MIN + " units"); } else { stock. Level = temp; } } Object-Oriented Principles in Java: Part I James Tam
How Does Hiding Information Protect The Class? (4) public boolean inventory. Too. Low () { if (stock. Level < CRITICAL) return true; else return false; } public void display. Inventory. Level () { System. out. println("No. items in stock: " + stock. Level); } } Object-Oriented Principles in Java: Part I James Tam
Implementation Hiding Allows you to use a program module (e. g. , a method) but you don’t care about how the code in the module (implementation) was written. For example, a list can be implemented as either an array or as a linked list. Object-Oriented Principles in Java: Part I James Tam
Implementation Hiding (2) List implemented as an array (add element) [0] 123 [1] 125 [2] 135 [3] 155 [4] [5] [6] [7] [8] [9] [10] 161 166 165 167 169 177 178 [11] Object-Oriented Principles in Java: Part I James Tam
Implementation Hiding (2) List implemented as an array (add element) [0] 123 [1] 125 [2] 135 [3] 155 [4] [5] [6] [7] [8] [9] [10] 161 166 array[5] = 165 167 169 177 178 [11] Object-Oriented Principles in Java: Part I James Tam
Implementation Hiding (3) List implemented as a linked list (add element) NIL Object-Oriented Principles in Java: Part I James Tam
Implementation Hiding (3) List implemented as a linked list (add element) NIL Object-Oriented Principles in Java: Part I James Tam
Implementation Hiding (3) List implemented as a linked list (add element) NIL Object-Oriented Principles in Java: Part I James Tam
Implementation Hiding (4) Changing the implementation of the list should have a minimal impact on the rest of the program The “add” method is a black box. We know how to use it without being effected by the details of how it works. add (list, new. Element) ? ? ? Object-Oriented Principles in Java: Part I James Tam
Instantiating Objects: The Constructor A method that is used to initialize objects as they are being instantiated (automatically called) If no constructor is specified then the default constructor is called e. g. , Sheep jim = new Sheep(); Object-Oriented Principles in Java: Part I James Tam
Creating Your Own Constructor Format: public <class name> (<parameters>) { // Statements to initialize the fields of the class } Example: public Sheep () { System. out. println("Creating "No name" sheep"); name = "No name"; } Object-Oriented Principles in Java: Part I James Tam
Overloading The Constructor Method overloading: • Creating different versions of a method • Each version is distinguished by the number, type and order of the parameters public Sheep () public Sheep (String name) • Different methods can have different return types (but must be distinguished from each other in another fashion) Object-Oriented Principles in Java: Part I James Tam
Using Constructors: An Example The complete example can be found in the directory /home/profs/tamj/233/examples/sheep. Class/version 1 class Sheep { private String name; public Sheep () { name = "No name"; } public Sheep (String name) { this. name = name; } Object-Oriented Principles in Java: Part I James Tam
Using Constructors: An Example (2) public String get. Name () { return name; } public void change. Name (String name) { this. name = name; } } Object-Oriented Principles in Java: Part I James Tam
Using Constructors: An Example (3) class Driver { public static void main (String [] argv) { System. out. println(); System. out. println("Creating herd. . . "); Sheep nellie = new Sheep ("Nellie"); Sheep bill = new Sheep("Bill"); Sheep jim = new Sheep(); jim. change. Name("Jim"); System. out. println("t"+ nellie. get. Name()); System. out. println("t"+ bill. get. Name()); System. out. println("t"+ jim. get. Name()); System. out. println(); } } Object-Oriented Principles in Java: Part I James Tam
We Now Have Several Sheep I’m Jim! I’m Bill! Object-Oriented Principles in Java: Part I I’m Nellie! James Tam
Question: Who Tracks The Size Of The Herd? Jim: Me! Bill: Me! Object-Oriented Principles in Java: Part I Nellie: Me! James Tam
Answer: None Of The Above Information about all instances of a class should not be tracked by an individual object So far we have used instance fields Each instance of an object contains it’s own set of instance fields which can contain information unique to the instance class Sheep { private String name; : : : } Name: Bill Object-Oriented Principles in Java: Part I Name: Jim Name: Nellie James Tam
Static: Revisted Static fields: One instance of the field exists for the class (not for the instances of the class) Class Sheep herd. Size object Name: Bill Object-Oriented Principles in Java: Part I object Name: Jim object Name: Nellie James Tam
Static: Revisted (2) Static methods (class methods): • Act on the class fields • Are associated with the class as a whole and not individual instances of the class Object-Oriented Principles in Java: Part I James Tam
Static Revisited: An Example The complete example can be found in the directory: /home/profs/tamj/233/examples/sheep. Class/version 2 class Sheep { // Class variable: Tracks the total number of sheep private static int herd. Size; // Instance variable: Unique to each individual sheep private String name; // Constructors public Sheep () { herd. Size++; System. out. println("Creating "No name" sheep"); name = "No name"; } Object-Oriented Principles in Java: Part I James Tam
Static Revisited: An Example (2) public Sheep (String name) { herd. Size++; System. out. println("Creating the sheep called " + name); this. name = name; } // Class method public static int get. Herd. Size () { return herd. Size; } // Instance methods public String get. Name () { return name; } Object-Oriented Principles in Java: Part I James Tam
Static Revisited: An Example (3) public void change. Name (String name) { this. name = name; } } Object-Oriented Principles in Java: Part I James Tam
Static Revisited: An Example (4) class Driver { public static void main (String [] argv) { System. out. println(); System. out. println("You have " + Sheep. get. Herd. Size() + " sheep"); System. out. println("Creating herd. . . "); Sheep nellie = new Sheep ("Nellie"); Sheep bill = new Sheep("Bill"); Sheep jim = new Sheep(); System. out. println("You now have " + Sheep. get. Herd. Size() + " sheep: "); jim. change. Name("Jim"); System. out. println("t"+ nellie. get. Name()); System. out. println("t"+ bill. get. Name()); System. out. println("t"+ jim. get. Name()); System. out. println(); } } Object-Oriented Principles in Java: Part I James Tam
Rules Of Thumb: Instance Vs. Class Fields If a field or information can differ between instances of a class: • The field probably should be an instance field If the field or information relates to the class or to all instances of the class • The field probably should be a static field of the class Object-Oriented Principles in Java: Part I James Tam
Rules Of Thumb: Instance Vs. Class Methods If a method acts on instance fields of individual objects: • The method should probably be an instance method If a method acts on static class fields or is not associated with multiple objects • The method should probably be a static class method Object-Oriented Principles in Java: Part I James Tam
Example Case: The System! There is one computer system on which a Java program is running on (not multiple instances of the system). public class System { public static final Print. Stream out; : } public class Print. Stream { public void print (boolean b); public void print (char c); : } Object-Oriented Principles in Java: Part I James Tam
Example Case: The System! There is one computer system on which a Java program is running on (not multiple instances of the system). public class System { public static final Print. Stream out; : } public class Print. Stream { public void print (boolean b); public void print (char c); : } Object-Oriented Principles in Java: Part I James Tam
Objects As Parameters In Java all parameters are passed by value Passing an object into a method actually passes a reference to the object Do changes to the object made in the method still exist after the method exist? • Answer: It depends! The following example can be found in the directory: /home/profs/tamj/233/examples/parameter. Example Object-Oriented Principles in Java: Part I James Tam
Objects As Parameters (2) class Integer. Wrapper { private int num; public void set. Num (int no) { num = no; } public int get. Num () { return num; } } Object-Oriented Principles in Java: Part I James Tam
Objects As Parameters (3) class Driver { public static void method. One (Integer. Wrapper iw) { Integer. Wrapper temp = new Integer. Wrapper (); temp. set. Num(10); iw = temp; System. out. println("Method One"); System. out. println("iw. num "+ iw. get. Num() + "t" + "temp. num " + temp. get. Num()); } public static void method. Two (Integer. Wrapper iw) { iw. set. Num(10); System. out. println("Method Two"); System. out. println("iw. num "+ iw. get. Num()); } Object-Oriented Principles in Java: Part I James Tam
Objects As Parameters (4) public static void main (String [] argv) { Integer. Wrapper iw = new Integer. Wrapper(); iw. set. Num(1); System. out. println("Main method"); System. out. println("iw. num "+ iw. get. Num()); System. out. println(); method. One(iw); System. out. println("Main method"); System. out. println("iw. num "+ iw. get. Num()); method. Two(iw); System. out. println("Main method"); System. out. println("iw. num "+ iw. get. Num()); } } Object-Oriented Principles in Java: Part I James Tam
Summary The difference between the Procedural and the Object. Oriented approaches? Some fundamental Object Oriented principles (in Java) • Classes and instances • Encapsulation • Hiding (information / implementation) • Fields unique to individual instances vs. data that is associated with the class • Instance methods vs. class methods (static) How are objects passed as parameters to methods? Object-Oriented Principles in Java: Part I James Tam
- Slides: 69