James Tam Object-Oriented Principles in Java: Part I Encapsulation Information Hiding Implementation Hiding Creating Objects in Java Class attributes.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

Written by: Dr. JJ Shepherd
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
James Tam CPSC 233: Introduction to Classes and Objects, Part I Attributes and methods Creating new classes References: Dynamic memory allocation and.
James Tam CPSC 233: Introduction to Classes and Objects Attributes and methods Creating new classes References: Dynamic memory allocation and automatic.
James Tam CPSC 233: Introduction to Classes And Objects, Part II More on Java methods Relations between classes Association Aggregation Multiplicity Issues.
James Tam Java Exception Handling Handling errors using Java’s exception handling mechanism.
James Tam CPSC 233: Introduction to Classes and Objects, Part I Attributes and methods Creating new classes References: Dynamic memory allocation and.
James Tam Object-Oriented Design Approaches to object-oriented design Some principles for good design Benefits and Drawbacks of the Object-Oriented Approach.
James Tam Data structures in Java Data Structures In Java In this section of notes you will learn about two common types of data structures: Queues Stacks.
Road Map Introduction to object oriented programming. Classes
James Tam Advanced Java Programming After mastering the basics of Java you will now learn more complex but important programming concepts as implemented.
James Tam Object-Oriented Principles in Java: Part II Issues associated with objects containing/composed of other objects: Composition, Reuse Issues associated.
James Tam CPSC 233: Introduction to Classes and Objects, Part II More on Java methods Relations between classes Association Aggregation Multiplicity Issues.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Class Design Lecture 6, Tue Jan
James Tam Java Exception Handling Handling errors using Java’s exception handling mechanism.
James Tam Introduction To Object-Oriented Programming Encapsulation Defining classes and instantiating objects Attributes and methods References and parameter.
James Tam Java Exception Handling Handling errors using Java’s exception handling mechanism.
James Tam Introduction To Object-Oriented Programming This section includes introductions to fundamental object-oriented principles such as information.
James Tam CPSC 233: Advanced Java And Object-Oriented Concepts More on Java methods Relations between classes Association Aggregation Multiplicity Issues.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
James Tam Advanced Relations Relationships between classes: Inheritance Access modifiers: Public, private, protected Interfaces: Types Vs. Classes Abstract.
James Tam CPSC 233: Introduction to Classes and Objects Attributes and methods Creating new classes References: Dynamic memory allocation and automatic.
James Tam Introduction To Object-Oriented Programming This section includes introductions to fundamental object-oriented principles such as information.
Abstract Classes and Interfaces
James Tam Introduction To Object- Oriented Programming This section includes introductions to fundamental object-oriented principles such as encapsulation,
CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]
Programming Languages and Paradigms Object-Oriented Programming.
Writing Classes (Chapter 4)
James Tam Advanced Java Programming After mastering the basics of Java you will now learn more complex but important programming concepts as implemented.
CSC 212 Object-Oriented Programming and Java Part 1.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
James Tam Introduction To Object- Oriented Programming Basic Object-Oriented principles such as encapsulation, overloading as well the object-oriented.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
10-Nov-15 Java Object Oriented Programming What is it?
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Applications Development
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Working With Objects Tonga Institute of Higher Education.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
James Tam Introduction To Object-Oriented Programming This section includes introductions to fundamental object-oriented principles such as information.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Written by: Dr. JJ Shepherd
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
James Tam Introduction To Object-Oriented Programming This section includes introductions to fundamental object-oriented principles such as information.
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
More Sophisticated Behavior
Chapter 3: Using Methods, Classes, and Objects
Object Based Programming
Advanced Java Programming
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object-Oriented Programming
Advanced Java Programming
Java Exception Handling
Presentation transcript:

James Tam Object-Oriented Principles in Java: Part I Encapsulation Information Hiding Implementation Hiding Creating Objects in Java Class attributes vs. instance attributes

James Tam Object-Oriented Principles in Java: Part I 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)

James Tam Object-Oriented Principles in Java: Part I An Example Of The Procedural Approach FileEditHelp … Creating new document Opening a document Saving a document … Exiting program PowerPoint

James Tam Object-Oriented Principles in Java: Part I An Example Of The Object-Oriented Approach Mummy Scorpion Dragon Screamer Ghost Knight Monsters Weapons Armour Broadsword Longbow Rapier Dungeon Master :

James Tam Object-Oriented Principles in Java: Part I Characteristics Of The Object-Oriented Approach Two are covered in this section of notes: Encapsulation Hiding (information / implementation)

James Tam Object-Oriented Principles in Java: Part I Characteristics Of The Object-Oriented Approach Two are covered in this section of notes: Encapsulation Hiding (information / implementation)

James Tam Object-Oriented Principles in Java: Part I Encapsulation “Grouping together under a name” You’ve already done this in CPSC 231: Problem decomposition: Procedures and functions in A5: Checkers Composite types: Records for A6 & A7: Movie list

James Tam Object-Oriented Principles in Java: Part I Encapsulation Through Procedures And Functions An example: Displaying the checker board

James Tam Object-Oriented Principles in Java: Part I Encapsulation Through Procedures And Functions An example: Displaying the checker board writeln(' ':19); for r := 1 to BOARDSIZE do begin writeln(' ':19); write(r:2, '|'); for c := 1 to BOARDSIZE do begin write(checkerBoard[r][c], '|'); end; writeln; end; writeln(' ':19); end

James Tam Object-Oriented Principles in Java: Part I Encapsulation Through Procedures And Functions An example: Displaying the checker board displayBoard(checkerBoard); procedure displayBoard (checkerBoard : Board); begin for r := 1 to BOARDSIZE do for c := 1 to BOARDSIZE do write(checkerBoard[r][c]); end;

James Tam Object-Oriented Principles in Java: Part I 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);

James Tam Object-Oriented Principles in Java: Part I 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(movieVariable);

James Tam Object-Oriented Principles in Java: Part I Encapsulation With The Procedural Approach (Pascal Records) Composite type (Records) Attributes (data) What the variable “knows”

James Tam Object-Oriented Principles in Java: Part I 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

James Tam Object-Oriented Principles in Java: Part I Example Objects: Monsters From Dungeon Master Dragon Scorpion Couatl

James Tam Object-Oriented Principles in Java: Part I Monsters: Attributes Represents information (may be common to all or unique to some): Name Speed Damage it inflicts Damage it can sustain :

James Tam Object-Oriented Principles in Java: Part I Monsters: Operations Represents what each monster can do Often unique to a type of monster Example Dragon Scorpion Stinger

James Tam Object-Oriented Principles in Java: Part I Monsters: Operations Couatl Serpent (poison) Wings

James Tam Object-Oriented Principles in Java: Part I Working With Objects In Java Define the class Declare an instance of the class (instantiate an object) Accessing different parts of an object

James Tam Object-Oriented Principles in Java: Part I Defining A Java Class Format: class { fields methods } Example: class Foo { int num; void displayNum () { System.out.println(num); }

James Tam Object-Oriented Principles in Java: Part I Instantiating Instances Of A Class Format: = new (); Example: Foo f = new Foo ();

James Tam Object-Oriented Principles in Java: Part I Accessing Parts Of A Class Format:. ; Example: Foo f = new Foo ();

James Tam Object-Oriented Principles in Java: Part I The Basics Of Classes: An Example Example (The complete example can be found in the directory /home/profs/tamj/233/examples/inventoryClass/version1): class Inventory { final int CRITICAL = 10; int stockLevel; void addToInventory (int amount) { stockLevel = stockLevel + amount; } void removeFromInventory (int amount) { stockLevel = stockLevel - amount; }

James Tam Object-Oriented Principles in Java: Part I The Basics Of Classes: An Example (2) boolean inventoryTooLow () { if (stockLevel < CRITICAL) return true; else return false; } void displayInventoryLevel () { System.out.println("No. items in stock: " + stockLevel); }

James Tam Object-Oriented Principles in Java: Part I The Basics Of Classes: An Example (3) import tio.*; class Driver { public static void main (String [] argv) { Inventory chinookInventory = new Inventory (); char menuOption; int amount; boolean temp; do { System.out.println("\n\nINVENTORY 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();

James Tam Object-Oriented Principles in Java: Part I The Basics Of Classes: An Example (4) System.out.print("Selection: "); menuOption = (char) Console.in.readChar(); Console.in.readChar(); System.out.println(); switch (menuOption) { case 'A': System.out.print("No. items to add: "); amount = Console.in.readInt(); Console.in.readChar(); chinookInventory.addToInventory(amount); chinookInventory.displayInventoryLevel(); break;

James Tam Object-Oriented Principles in Java: Part I The Basics Of Classes: An Example (5) case 'R': System.out.print("No. items to remove: "); amount = Console.in.readInt(); Console.in.readChar(); chinookInventory.removeFromInventory(amount); chinookInventory.displayInventoryLevel(); break; case 'D': chinookInventory.displayInventoryLevel(); break;

James Tam Object-Oriented Principles in Java: Part I The Basics Of Classes: An Example (6) case 'C': temp = chinookInventory.inventoryTooLow(); if (chinookInventory.inventoryTooLow()) System.out.println("Stock levels critical!"); else System.out.println("Stock levels okay"); chinookInventory.displayInventoryLevel(); break; case 'Q': System.out.println("Quitting program"); break; default: System.out.println("Enter one of A, R, D, C or Q"); } } while (menuOption != 'Q'); }

James Tam Object-Oriented Principles in Java: Part I Characteristics Of The Object-Oriented Approach Two are covered in this section of notes: Encapsulation Hiding (information / implementation)

James Tam Object-Oriented Principles in Java: Part I Information Hiding Protects the inner-workings (data) of a class Only allow access to the core of an object in a controlled fashion

James Tam Object-Oriented Principles in Java: Part I 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 ; Example: private int num; Rule of thumb: Unless there is a compelling reason, the data for a class should be hidden (private)

James Tam Object-Oriented Principles in Java: Part I 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) Format: public ( ) method data

James Tam Object-Oriented Principles in Java: Part I Accessing Hidden Information (2) Example: public void addToInventory (int amount) { stockLevel = amount; }

James Tam Object-Oriented Principles in Java: Part I 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/inventoryClass/version2

James Tam Object-Oriented Principles in Java: Part I 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 stockLevel;

James Tam Object-Oriented Principles in Java: Part I How Does Hiding Information Protect The Class? (2) public void addToInventory (int amount) { int temp; temp = stockLevel + amount; if (temp > MAX) { System.out.print("Adding " + amount + " item will cause stock "); System.out.println("to become greater than " + MAX + " units"); } else { stockLevel = stockLevel + amount; }

James Tam Object-Oriented Principles in Java: Part I How Does Hiding Information Protect The Class? (3) public void removeFromInventory (int amount) { int temp; temp = stockLevel - 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 { stockLevel = temp; }

James Tam Object-Oriented Principles in Java: Part I How Does Hiding Information Protect The Class? (4) public boolean inventoryTooLow () { if (stockLevel < CRITICAL) return true; else return false; } public void displayInventoryLevel () { System.out.println("No. items in stock: " + stockLevel); }

James Tam Object-Oriented Principles in Java: Part I 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.

James Tam Object-Oriented Principles in Java: Part I Implementation Hiding (2) List implemented as an array (add element) [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

James Tam Object-Oriented Principles in Java: Part I Implementation Hiding (2) List implemented as an array (add element) [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] array[5] = 165

James Tam Object-Oriented Principles in Java: Part I Implementation Hiding (3) List implemented as a linked list (add element) NIL

James Tam Object-Oriented Principles in Java: Part I Implementation Hiding (3) List implemented as a linked list (add element) NIL

James Tam Object-Oriented Principles in Java: Part I Implementation Hiding (3) List implemented as a linked list (add element) NIL

James Tam Object-Oriented Principles in Java: Part I 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, newElement)

James Tam Object-Oriented Principles in Java: Part I 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();

James Tam Object-Oriented Principles in Java: Part I Creating Your Own Constructor Format: public ( ) { // Statements to initialize the fields of the class } Example: public Sheep () { System.out.println("Creating \"No name\" sheep"); name = "No name"; }

James Tam Object-Oriented Principles in Java: Part I 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)

James Tam Object-Oriented Principles in Java: Part I Using Constructors: An Example The complete example can be found in the directory /home/profs/tamj/233/examples/sheepClass/version1 class Sheep { private String name; public Sheep () { name = "No name"; } public Sheep (String name) { this.name = name; }

James Tam Object-Oriented Principles in Java: Part I Using Constructors: An Example (2) public String getName () { return name; } public void changeName (String name) { this.name = name; }

James Tam Object-Oriented Principles in Java: Part I 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.changeName("Jim"); System.out.println("\t"+ nellie.getName()); System.out.println("\t"+ bill.getName()); System.out.println("\t"+ jim.getName()); System.out.println(); }

James Tam Object-Oriented Principles in Java: Part I We Now Have Several Sheep I’m Bill!I’m Nellie!I’m Jim!

James Tam Object-Oriented Principles in Java: Part I Question: Who Tracks The Size Of The Herd? Bill: Me!Nellie: Me! Jim: Me!

James Tam Object-Oriented Principles in Java: Part I 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: JimName: NellieName: Bill

James Tam Object-Oriented Principles in Java: Part I Static: Revisted Static fields: One instance of the field exists for the class (not for the instances of the class) Name: Bill object Name: Jim object Name: Nellie object Class Sheep herdSize

James Tam Object-Oriented Principles in Java: Part I 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

James Tam Object-Oriented Principles in Java: Part I Static Revisited: An Example The complete example can be found in the directory: /home/profs/tamj/233/examples/sheepClass/version2 class Sheep { // Class variable: Tracks the total number of sheep private static int herdSize; // Instance variable: Unique to each individual sheep private String name; // Constructors public Sheep () { herdSize++; System.out.println("Creating \"No name\" sheep"); name = "No name"; }

James Tam Object-Oriented Principles in Java: Part I Static Revisited: An Example (2) public Sheep (String name) { herdSize++; System.out.println("Creating the sheep called " + name); this.name = name; } // Class method public static int getHerdSize () { return herdSize; } // Instance methods public String getName () { return name; }

James Tam Object-Oriented Principles in Java: Part I Static Revisited: An Example (3) public void changeName (String name) { this.name = name; }

James Tam Object-Oriented Principles in Java: Part I Static Revisited: An Example (4) class Driver { public static void main (String [] argv) { System.out.println(); System.out.println("You have " + Sheep.getHerdSize() + " 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.getHerdSize() + " sheep:"); jim.changeName("Jim"); System.out.println("\t"+ nellie.getName()); System.out.println("\t"+ bill.getName()); System.out.println("\t"+ jim.getName()); System.out.println(); }

James Tam Object-Oriented Principles in Java: Part I 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

James Tam Object-Oriented Principles in Java: Part I 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

James Tam Object-Oriented Principles in Java: Part I 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 PrintStream out; : } public class PrintStream { public void print (boolean b); public void print (char c); : }

James Tam Object-Oriented Principles in Java: Part I 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 PrintStream out; : } public class PrintStream { public void print (boolean b); public void print (char c); : }

James Tam Object-Oriented Principles in Java: Part I 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/parameterExample

James Tam Object-Oriented Principles in Java: Part I Objects As Parameters (2) class IntegerWrapper { private int num; public void setNum (int no) { num = no; } public int getNum () { return num; }

James Tam Object-Oriented Principles in Java: Part I Objects As Parameters (3) class Driver { public static void methodOne (IntegerWrapper iw) { IntegerWrapper temp = new IntegerWrapper (); temp.setNum(10); iw = temp; System.out.println("Method One"); System.out.println("iw.num "+ iw.getNum() + "\t" + "temp.num " + temp.getNum()); } public static void methodTwo (IntegerWrapper iw) { iw.setNum(10); System.out.println("Method Two"); System.out.println("iw.num "+ iw.getNum()); }

James Tam Object-Oriented Principles in Java: Part I Objects As Parameters (4) public static void main (String [] argv) { IntegerWrapper iw = new IntegerWrapper(); iw.setNum(1); System.out.println("Main method"); System.out.println("iw.num "+ iw.getNum()); System.out.println(); methodOne(iw); System.out.println("Main method"); System.out.println("iw.num "+ iw.getNum()); methodTwo(iw); System.out.println("Main method"); System.out.println("iw.num "+ iw.getNum()); }

James Tam Object-Oriented Principles in Java: Part I 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?