Download presentation
Presentation is loading. Please wait.
1
Object-Oriented Design and Development
Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 371 Fairfield Road, Box U-255 Storrs, CT (860) Copyright © 2000 by S. Demurjian, Storrs, CT.
2
Abstraction
3
Encapsulation
4
What is a Class?
5
Agile Development
6
Software Cost Estimation
7
Object-Oriented Paradigm
Object-Oriented Decomposition Decompose Problem into Agents which Perform Operations Emphasize Agents that Cause Actions Agents Comprised of Two Parts Hidden Implementation: Data and Operations only Available to Agent Public Interface: Operations Available to Clients of Agent An Agent Can Only be Modified by Operations Defined in either the Hidden Implementation or Public Interface
8
Core Object-Oriented Concepts
Class The Type of an Agent Describes the Behavior Object The Instance of a Class Represents Actual Data Manipulated by Agents Maintains the State of Object Method Operation Defined on a Class Operates on ALL Instances of the Class Message Indicates that an Object’s Method Invoked
9
What is a Class ? A class is a generalized description of
occurrences roles things organizational units places external entities structures A class is a generalized description of a collection of similar objects. Object is an instance of a class. Class exports: -Operations used to manipulate instances -May export attributes. class name attributes: operations:
10
Two Representations of a Class
11
Operations (or Methods or Services) Defined on a Class
An executable procedure that is a part of a class and operates on the data attributes defined as part of the class A method operates on all instances of a class A method is invoked via message passing
12
Messages - the means by which objects invoke each other’s methods.
13
An Example Employee Class
Class Employee { } Main() { //Declare Objects Employee emp1(Steve,100.0); Employee emp2(Lois, 120.0); //Pass Messages //Invoke Methods emp1.print_name(); emp1.print_salary(); emp2.update_salary(10); emp2.print_name(); emp2.print_salary(); } //Hidden Implementation Private: //Instance Vars char[30] name; float salary; //Public Interface Public: void print_name(); void print_salary(); void update_salary(float i); Employee(char *n, float s); What’s Output of Main()? Conclusion: Each Object (emp1,emp2) has Own Independent State that is Accessible via Shared Public Interface of Class Steve 100.0 Lois 130.0
14
Object-Oriented Concepts
Background and Motivation Transitional Design & Silver Bullet (Brooks) Law of Demeter/Responsibility-Driven Design Object-Oriented Design Issues The High-Tech Supermarket System (HTSS) Choosing Objects and Classes Inheritance and Overloading Polymorphism/Dynamic Binding Generic: A Type Parameterizable Class “Software Design,” and “Object-Oriented Design”, Chapter 108 and 109, The Computer Science & Engineering Handbook, Tucker (ed.), CRC Press, 2nd Edition, 2002.
15
Objects vs. ADTs Objects Extend ADTs as follows:
Message Passing: Object Activation by a Request (Method Call) to Perform an Action Inheritance: Sharing of Code Among Objects Polymorphism: Shared Code Behaves Differently Based on Object and Context ADT/OO Benefits: Support Creation of Reusable Software Components Creation and Testing in Isolation! SEs View Problem at Higher-Level of Abstraction
16
Choosing Objects and Classes
The ‘First’ and Most ‘Often’ Concern for Newcomers to OO Concepts Typical Answers: High Cohesion, Low Coupling, Encapsulation Law of Demeter, Responsibility-Driven Design Comes with Experience and Time Better Answer: Choosing Objects/Classes Not a First Step Can't Jump to High-Level/Detailed Design Choice Guided by Specification - Contains Intent and Requirements DFDs, ERs, Interfaces, User Interactions, etc.
17
Choosing Objects and Classes
Employee class Private data: Name Address SSN Salary Public interface: Create_employee() Give_Raise_Amount(Amount) Change_Address(New_Addr) Based on an information perspective, focusing on the idea that to track Employees a set of standard data and operations are needed
18
Choosing Objects and Classes
ATM_log class: Private data: Acct_name PIN_number Public interface: Check_database(Name) Verify_PIN(PIN) Log_on_Actions(Name,PIN) Reject() Embodies the functions that take place to authenticate an individual to an ATM session Even with a functional view, information is needed to capture user input for verifying status
19
Choosing Objects and Classes
ATM_User: Private data: Action Balance WD_Amt Public interface: Log_on_Steps() Acct_WithD() Check_Balance(Number) Deposit_Check() User interface by capturing the different interactions between the ATM and the user
20
Choosing Objects and Classes
Start from the problem specification Objects include physical entities as well as concepts such as seating arrangement, payment schedule Not all classes maybe explicit in the problem statement and may rely on domain knowledge for identification Objects frequently correspond to nouns in the statement
21
Choosing Objects and Classes
An appointments system that will allow telephone callers to book an appointment with a doctor. The caller will specify the day and the time when he wishes to be seen by a doctor. Tentative classes could be: Appointment, system, telephone, caller, doctor, day, time Patient - from domain knowledge Caller and patient express the same information but one is more meaningful in the context.
22
Choosing Objects and Classes
Identifying operations: Attributes Events in the scenarios Real-world behavior Attributes: Need operations to set and read attributes Events in the scenarios: A scenario consists of interactions (events exchanged) that have to take place among the objects to achieve the functionality. Identify common and rare scenarios. Events passed to and from the objects implies operation on the object or message from it.
23
Choosing Objects and Classes
Real world can also suggest the operations needed to support a class : Useful in broadening the scope of the class beyond its immediate application. Operations should not overlap each other: Use simple operations to create more complex activities e.g an edit operation could consist of copy, delete and insert. Number of operations that have access to the data should be reduced to a minimum. Operations may refer to verbs in the problem description
24
Inheritance – Example #1
A vehicle registration system maintains registration information about all types of vehicles owned by individuals. These include the ones that run on land, sail in water and fly in the air. The vehicles that run on the land include cars and trucks, the vehicles that sail in the water include sailboats, ships, motorboats and yatchs, and the vehicles that fly in the air include airplane and helicopters. Construct an inheritance hierarchy for the vehicle registration system.
25
Inheritance – Example #2
Consider a shipping cost calculation system that calculates shipping costs for a batch of packages. Packages can be shipped via three methods, namely, US Mail, FedEx or UPS. For each of these three methods, the customer has a choice of using either standard or priority shipping. The calculation of the shipping costs differs depending on which method is used. Construct an inheritance hierarchy for the shipping cost system.
26
Choosing Objects for BlackJack
Consider ‘Naïve’Abstraction: Deck Hand Game | Shuffle | | Play | | | | Deal | | Hit | | |Hand| |Hand| ... | | Hit | | Stand | | | | | | | | Operations? | What's Been Ignored? Multiple Decks of Cards? Modeling of Deck - Suits/Cards? Strategy for House? Moral: Objects/Classes are Not a Panacea for Comprehensive, Up-Front, Problem Exploration via a Detailed Specification
27
Object-Oriented Design Issues
The High-Tech Supermarket System (HTSS) Description of Capabilities Modules and ADTs for HTSS Categories of Classes Common Design Flaws
28
High-Tech Supermarket System (HTSS)
Automate the Functions and Actions Cashiers and Inventory Updates User Friendly Grocery Item Locator Fast-Track Deli Orderer Inventory Control User System Interfaces Cash Register/UPC Scanner GUI for Inventory Control Shopper Interfaces Locator and Orderer Deli Interface for Deli Workers We’ll Introduce and Utilize Throughout Course
29
The HTSS Software Architecture
SDO EDO IL Item SDO EDO IL ItemDB Local Server IL Payment CR CR IC Order CR Non-Local Client Int. IC CR IL: Item Locator CR: Cash Register IC: Invent. Control DO: Deli Orderer for Shopper/Employee CreditCardDB Inventory Control ATM-BanKDB ItemDB Global Server OrderDB SupplierDB
30
Categories of Classes Data Managers - Maintain Data/State Information
Contains Functionality for Application class Item { private: // Private Data int UPC; char* Name; int InStock, OnShelf, ROLimit; float RetailCost; public: // Public Methods Item(int code, char* str, int st1, int st2, int st3, float cost); void CreateNewItem(); int GetUPC(); char* GetName(); int GetQuantity(); int CheckReorderStatus(); void PrintItem(); void UpdatePrice(float new_value); };
31
Categories of Classes Data Sinks/Data Sources - Produce/Process Data
Generated on Demand or Maintained class ItemDB {private: int Num_Items; int Curr_Item; Item* AllItems[Max_Items]; int FindFirstItem(); int FindNextItem(); int FindItemUPC(int code); int FindItemName(char* name); public: ItemDB(); // Constructor void InsertNewItem(Item* new_one); void DeleteExistingItem(int code); void FindDisplayItemUPC(int code); void FindDisplayItemName(char* name); void PrintAllItems(); };
32
Categories of Classes Data Manager Class Item Class Contains the State of a Single Object Item I1, I2, I3; Data Source/Sink Class ItemDB is a Collection or Set of Items Item ItemDB[100]; ItemDB I1 “milk” I2 “peas” I3 “soda”
33
Categories of Classes View/Observer - Provide an Interface for User
Often Collects Information via Public Interface of Multiple Classes InvControlGUI Utilizes Item, ItemDB, etc. class InvControlGUI { private: int Curr_Option; // Current menu option public: InvControl(); // Constructor void PrintMenuSetOption(); void ActivateController(); void EnterNewItem(); void RemoveExistingItem(); void FindItem(); void InvSearchQuantity(); void InvSearchReorder(); void GenerateAnOrder(); };
34
Categories of Classes Facilitator/Helper - Used to Support Complex Tasks E.g., GUI Libs, Strings, I/O Handler, etc. For HTSS, Facilitator/Helpers as Follows: GUI Classes to Display Windows, Menu Options, Dialog Boxes, etc., for HTSS GUIs Linked List or Collection Classes to Allow Data to be Stored in ItemDB Is UPC Scanner a Facilitator/Helper Class?
35
Methodological Issues for OO Design
Design Grows Over Time Begin by Identifying Classes Vital to Application Simulate Scenarios of Expected Operation Identify New Classes Assign/Revise Methods to Classes Classes Demonstrate Flow of Control Experimental Approach to Design - Advantages Group Approach to Problem Solving Communication between Team Members Alternative Design Evaluation Completeness of Design High-Level yet Means for Details
36
Early Stage of OO Design
Class A Class B Class C Class D Class E Class B Class A Class C Class F
37
Methodological Issues
From First/Initial Attempts, Classes are Evolved Towards “Complete” Design Addition of New Classes Expand with New Methods Fine Tune Relationships Add/Refine “Hidden” Data Combine “Small/Similar” Classes Split “Large/Poorly Abstracted” Classes As Time Goes on, Include Inheritance: One Class is a Specialization of Another Class Aggregation: One Class is a Component of Another Class
38
Later Stage of OO Design
Class D Class E Real M, N; String S; Int X, Y; Char Z; Class B Method B1 Method B2 Method B3 Method B4 Class A Method A1 Method A2 Method A3 Class C Method C1 Method C2 Class F
39
Common Design Flaws Classes that Directly Modify the Private Data of Other Classes Provide Operations in Public Interface Only Change via Operations Asking Class to Change Itself Recall Item from HTSS Only Change RetailCost via UpdatePrice() Do not Access RetailCost Directly from Cashier class Item { private: // Private Data float RetailCost; public: // Public Methods void UpdatePrice(float new_value); };
40
Common Design Flaws Too Much Functionality in One Class
Class Grows Over Time - Not Cohesive Split a Class into Two or More Classes class Item { protected: // Attributes as given in earlier examples public: // Two constructors for versatility int GetUPC(); char* GetName(); int GetInstockAmt(); int GetOnShelfAmt(); int GetQuantity(); int GetReorderAmt(); float GetRetailPrice(); float GetWholeSaleCost(); void UpdateName(char* item_name); void UpdateInstockAmt(int stock_amt); void UpdateOnShelfAmt(int shelf_amt); void UpdateReorderAmt(int reord_amt); void UpdateRetailPrice(float price); void UpdateWholeSaleCost(float wholesale); } virtual void CreateNewItem(); virtual void PrintItem(); virtual void PrintPerish(); virtual void UpdateItemMenu(); virtual void UpdateItem(int portion); virtual char* ReturnType(); void PrintUPCName(); void PrintNamePrice(); void PrintInventory(); void PrintProfitInfo(); void PrintUPC(); void PrintName(); void PrintInstockAmt(); void PrintOnShelfAmt();
41
Common Design Flaws A Class that Lacks Functionality
Class Included at Early Design Stage Merge Two or More Classes Impact on Inheritance Hierarchies? Classes that Have Unused Functionality Eliminate Unused Functions and Reevaluate Their Necessity Classes that Duplicate Functionality Combine with Existing Class Add Non-Duplicate Functionality
42
Advanced Object-Oriented Concepts
Inheritance Controlled Sharing of Between Classes Generalization and Specialization Treat Instances of Different Classes in Uniform Fashion - Leading to … Polymorphism/Dynamic Binding Run-Time Choice of the Method to be Invoked Based on the Type of the Calling Instance Message Passed is Type Dependent Generic: A Type Parameterizable Class Stack has Parameter for Type of Element Creation of Program Variable Binds Stack Data and Methods to Specific Type of Element Stack(Real), Stack(Int), Stack(Employee)
43
Motivating Inheritance Concepts
Consider a University Application Four Classes Have Been Identified Faculty Dean UnderGrad Grad Name Name Name Name SSN SSN SSN SSN Rank School Dorm Dorm Dept Dept Year Program Yrs Yrs GPA Degree GPA To Successfully Utilize Inheritance Distinguish Differences (Specialization) Identify Commonalties (Generalization)
44
Motivating Inheritance
One Solution: Person Faculty:Person Dean:Person Name Rank School SSN Dept Dept Yrs Yrs UnderGrad:Person Grad:Person Dorm Dorm Year Program GPA Degree GPA Pictorially: Person Faculty Dean UnderGrad Grad Is this Solution Adequate?
45
Motivating Inheritance
A Better Solution: Person Name SSN Employee Student Dept Dorm Yrs GPA Faculty Dean UnderGrad Grad Rank School Year Program Degree Solution Utilizes Single Inheritance Exactly One Parent for Each Class Are we Done?
46
Motivating Inheritance
Revising Example: Person Name SSN Employee Student Dept Dorm Yrs GPA Faculty Dean UnderGrad Grad Rank School Year Program Degree Superclass, Supertype, Parent, Base Class Subclass, Subtype, Child, Derived Class Descendants, Ancestors, Siblings
47
Defining Inheritance Subclass Acquires Information and/or Operations of a Superclass Inheritance is a Transitive Operation Behavior and Information of a Subclass is a Superset of its Ancestors Subclass is More Refined than Superclass - its Specialized Superclass contains Common Characteristics of its Subclasses - its Generalized
48
Defining Inheritance Inheritance is Utilized when Two or More Classes are Functionally and/or Informationally Related In University Example, Common Data Basis of Inheritance Decision Other Bases for Inheritance could be: Common Methods Common Data and Methods Reuse Occurs from both Informational and Functional Perspective Information - No Replicated Variables Function - No Replicated Code
49
The Role of Inheritance
Develop Inheritance Hierarchies that are Extensible Reusable Evolvable Focus on5 Utilization of Inheritance: How Benefits of Inheritance: Why Impact of Inheritance: Cost We’ll Review this Material
50
Specialization and Generalization Inheritance
Most Common form of Inheritance to Refine the Behavior of the SuperClass Differences are Pushed Down Hierarchy Allows Designers to Customize Classes Generalization Inverse of Specialization Commonalities of Multiple Classes are Abstracted out to Form a SuperClass
51
Examples from HTSS Specialization and Generalization
Item / \ / \ NonPItem PerishItem / \ \ / \ \ DeliItem DairyItem ProduceItem Specialization Generalization class DeliItem : public PItem {protected: float Weight; float CostPerLb; void ItemSpecificPrint(); public: virtual void CreateNewItem(); virtual void PrintItem(); virtual void PrintPerish(); virtual void UpdateItem(); void PrintWeightandCost(); }; class PItem : public Item { protected: food_state Environ; int Days; void ItemSpecificPrint(); public: virtual void CreateNewItem(); virtual void PrintItem(); virtual void PrintPerish(); virtual void UpdateItem(); void PrintDaysFoodState(); };
52
Specification Inheritance & Example
Classes Share Common Interface (Superclass) Specification Class: An Abstract Interface Similar to Java’s Interface Designers Construct Unified Interface that is Sharable by Multiple Team Members Data-Oriented Function-Oriented GraphicalObject / \ \ / \ \ Ball Wall Hole Menu / \ / \ PrintMenu SaveMenu
53
Construction Inheritance & Example
Subclass Inherits Majority of Functionality from its Superclass Subclass may Extend, Limit, or Vary the Functionality of Superclass LinkedList / \ \ / \ \ Queue Set Stack Dictionary / \ / \ SymbolTable HashTable
54
Variance Inheritance & Example
Classes have Similar Implementations but Unrelated Abstract Views Result May Not Directly Aid Designer PointingDevice / \ \ / \ \ TouchPad Mouse Tablet Key Issues Share Common Abstraction Different Implementations Methods in TouchPad, Mouse, etc., Override Methods in PointingDevice
55
Combination Inheritance & Example
Use of Multiple Inheritance Combines Two or More Parents Allows Designers to View Design from Different Perspectives Faculty Student \ / \ / TeachingAsst MeatItem ProduceItem \ / \ / DelItem
56
Extension Inheritance & Example
New Abilities are Added to Subclass Allows Designers to Reuse Prior Designs Requires Method(s) of Superclass to be Overridden Window / \ / \ FixedColorW VarColorW | BWWindow Key Issues Going from 1 to 2 Colors FixedColorW - BWWindow Expanding Capabilities
57
Limitation Inheritance & Example
Subclass has more Restricted Behavior Typically to Extend Existing Class Library Inverse of Extension Also Supports Design Reuse DEQueue / \ / \ Queue Stack / \ LIFO FIFO Key Issues Going from Two-Direction Queue to Ltd. Abstractions Limiting Functionality
58
Memory Layout Inheritance
Person String: Name String: Addr Undergrad Instance: ug1 Name: “John” Addr: “23 Main Street” GPA: Dorm: “ Buckley” Major: “ Computer Science” Student Float: GPA Undergrad String: Dorm String: Major
59
Memory Layout Inheritance
Student: String: Name String: Addr Enum: College Profile myInfo Student Instance: s1 Name: “John” Addr: “23 Main Street” myInfo: Profile Instance: p1 GPA: Dorm: “ Buckley” Major: “ Computer Science” Profile Float: GPA String: Dorm String: Major
60
Benefits of Inheritance
Software Reusability Inherited Characteristics Often Represents Compiled and Tested Code/Behavior Reuse in Future Products Design and Program Families Design and Code Sharing Two or More Subclasses of the Same Superclass Share Code Redundancy is Reduced Reliability/Testing Enhanced Inherit from Existing Subclass that has been Utilized and Exercised
61
Benefits of Inheritance
Software Components Promotes the Concept of Reusable Components and Software Factory Combine Rather than Construct JavaBeans and APIs, Ada95 Packages, etc. Rapid Prototyping Utilization of Reusable Components Incremental Design and Development Delivery of Multiple Prototypes Faster to Market All Benefits Apply to Design, Development, and Maintenance!
62
The Cost of Inheritance
Execution Speed Compile-Time Overhead Due to Inheritance Many Decisions Related to Inheritance Must Occur at Runtime We’ll Explore this Shortly Program Size Libraries are Large, and if Only Static Linking, Size Grows Good News: Dynamic Linking Techniques are Improving Improve Runtime Environment Platform Independence (Java) Impacts both Speed and Size
63
The Cost of Inheritance
Message Passing Overhead An Overuse of Messages is akin to an Overuse of Procedures/Functions in C or Pascal Messages that Pass Arrays Increase Overhead To Find “Correct” Method, Must Search Object, Parent, Grandparent, etc. Remote Messages for Distributed Object Computing (CORBA, Java RMI) Program Complexity For Any New Paradigm, Software Engineers Must Acquire Appropriate Skills Despite HW Increases, Software Size and Complexity Continues to Grow!
64
Overloading The Ability to Define Two or More Methods with the Same Names and Different Signatures A Feature of Programming Language Available in OO and Non-OO Languages Present in Current Languages, e.g., ‘+’ Means Integer Addition Real Addition Set Union (Pascal) OO Design and Programming Allows us to Define our own Types (Classes) Overload Operations (+, -, *, ++, etc.) Overload Methods
65
Overloading in a Stack Example
class stack { private: char* st, top; int size; public: void stack(int x) {top = st = new char[x]; size = x;} void stack() {top = st = new char[100]; size = 100;} // push, pop, top, etc., Omitted }; main() { stack S1(10); // Creates a char Stack with 10 Slots stack S2; // Default, no Parameter Supplied // Creates a char Stack with 100 Slots // Size of S2 Might not be Known to User! } S1 20 15 10 5 S2 … etc ... 20 15 10 5
66
Overloading in HTS class Item { private:
int UPC, OnShelf, InStock, ROLimit; // Etc... As Previously Given public: Item(); // The Constructor // Etc... Others as Previously Given Item operator--(){ this->OnShelf--; this->InStock--; } }; main() { Item I1; Status s; s = I1.Create_New_Item(123, OJ, 10, 30, ...); I1--; // Reduces I1.OnShelf and I1.InStock // Now Contain 9 and 29 Respectively }
67
Important Implementation Concepts
Message Passing Method is a Member Function Message Passing: Invoking a Method receiverObject.MemberFunctionName( Automatic Variables Created within Function/Released at End Stack-Based Allocation No User Control/Intrevention Dynamic Variables Created on Demand by Explicit Invocation Heap-Based Allocation May Require Memory Management Why are A/D Variables Important to Design?
68
Important Implementation Concepts
Lifetime: Execution Period that Space Must Remain Allocated to Variable Scope: Portion of Program in Which Variable May Appear and be Utilized Immutable Values: Assigned Once, Can’t Change Constants Known at Compile Time Immutable Values Set at Runtime (UPC Code) Typing of Variables Static (Compile): C++, Java, Ada95 Dynamic (Runtime): Smalltalk, Lisp, … Strongly-Type Languages (Ada95 and Java) Language Does Not Allow Variable of One Type to hold Value of Different Type
69
Important Implementation Concepts
Static Binding: Method Bound to Message Based on Characteristics of Variable SE Must Track Type of Object Method Looked-Up at Compile Time Compile Detects Inappropriate Method Calls Dynamic Binding: Method Bound to Message Based on Characteristics of Value (Object) Runtime Search for Type of Object When Message is Passed (Method is Invoked) May Yield Runtime Error May Find/Execute “Inappropriate” Method Late Binding: Matching Message Invoked to Correct Method at Runtime
70
Remaining Object-Oriented Concepts
Polymorphism Definition and Illustration Attainment and Benefits Generics Type-Parameterizable Classes Examples using C++ Concepts that Impact Design and Development Substitutability Mutability Specialization via Constraints Material from “Fundamentals of Object-Oriented Databases”, pgs. 1-34, Zdonik/Maier.
71
Defining Polymorphism
Polymorphism is the Ability of a Variable to Hold more than One Type of Value, e.g., Subtypes of a Common Parent Variables P: Person; F: Faculty; S: Student; //Supertype can Hold Instance of //Subtype, but NOT REVERSE! P = F; // Treat Faculty as Person P = S; // Treat Student as Person P F S
72
Definition of Polymorphism/Dispatching
Polymorphism via Dispatching Allows a Runtime or Dynamic Choice of the Method to be Called based on the Class Type of the Invoking Instance Concept is only Useful in the Context of Inheritance Benefits of Polymorphism/Dispatching: Offers More Versatility in Hierarchy and Code Development Promotes Reuse and Evolution of Code Makes Code More Generic and Easier to Develop and Debug Polymorphism/Dispatching Incurs Cost or Overhead at both Compile and Runtime!
73
Illustrating Polymorphism/Dispatching
Consider Previous Example Person Name SSN Employee Student Dept Dorm Yrs GPA Faculty Dean UnderGrad Grad Rank School Year Program Degree Define Print_Info Method for Each Class Can Correct Print_Info Method be Called Automatically Based on Type of Instance Variable?
74
Illustrating Polymorphism/Dispatching
E S F D U G Steve Lois Tom Mary Ed Person Object Repository “Faculty” “Dean” “UnderGrad” “Graduate” What’s True About Each Person?
75
Illustrating Polymorphism/Dispatching
Print_Info Methods Defined as Follows: Person::Print_Info() {Prints Name and SSN} Employee::Print_Info() {Calls Person::Print_Info(); Prints Dept and Yrs; } Student::Print_Info() Prints Dorm and GPA; } Faculty::Print_Info() {Calls Employee::Print_Info(); Prints Rank; } Print_Info Also for Dean, UnderGrad, Grad
76
Illustrating Polymorphism/Dispatching
Suppose Iterate Through Instances of Person Repository For Each Instance, Call Method Print_Info() How Does One Determine the “Correct” Method to Call? What are the Compile Time Checks? Compile Time Guarantee? Runtime Checks? Person Object Repository Steve Lois “Faculty” “Graduate” Ed Tom “Faculty” “UnderGrad” Mary “Dean”
77
Achieving Polymorphism/Dispatching
Build a Mixed List of Instances of Differing Types that Share a Common Ancestor To Begin, Declare Variables: FA1 = Faculty(Steve, 111, CSE, 7, AssocP); UG1 = UnderGrad(Rich, 222, Towers, 3.5, Senior); GR1 = Grad(Don, 333, OffCampus, 3.75, CSE, PhD); Define a LIST Class of Persons LIST is a Collection Class that Allows a Set of One or More Person Instances to be Stored LIST is an OO Version of Linked List Define LIST Methods for: LIST::Add_Person(Person P); LIST::Print_A_Member();
78
Achieving Polymorphism/Dispatching
LIST Class has the Method Implementation LIST::Print_A_Member() { Calls Print_Info(); } Augment Variable Declarations with: PTR = POINTER TO CLASS FOR A LIST OF Persons; PTR -> LIST::Add_Person(GR1); //Add ‘Don’ PTR -> LIST::Add_Person(UG1); //Add ‘Rich’ PTR -> LIST::Add_Person(FA1); //Add ‘Steve’ PTR Views All List Elements as Persons Person is Common (Root) Ancestor Shared by All Classes in Inheritance Hierarchy!
79
Achieving Polymorphism/Dispatching
Pictorially, a LIST of Persons is Created: | Person | | Person | | Person | PTR ->| |-->| |-->| | | (Really | | (Really | | (Really | | Steve | | Rich | | Don | | Faculty) | |Undergrad)| | Grad) | What Happens when PTR->Print_A_Member()? If PTR Referencing ‘Steve’ Instance? If PTR Referencing ‘Rich’ Instance? If PTR Referencing ‘Don’ Instance? When PTR->Print_A_Member()is Called, Recall that the Print_Info() Method is Invoked
80
Execution/Runtime Sequence of Polymorphism/Dispatching
Which Print_Info Method is Invoked? The Runtime Environment Dynamically Chooses the Correct Method Based on Instance Type When PTR References ‘Steve’/Faculty Instance then Faculty::Print_Info() When PTR References ‘Rich’/UnderGrad Instance then UnderGrad::Print_Info() When PTR References ‘Don’/Grad Instance then Grad::Print_Info() Runtime Environment will Also Check Ancestor Instances In Order to Find the Correct Method Correct Compilation Guarantees Method Will be Found at Runtime!
81
Benefits of Polymorphism/Dispatching
Focus on Extensibility! Easily Extend and Evolve the Class/Inheritance Hierarchy as New Kinds of Items are Needed Extension/Evolution Occurs without Recompilation of Person Class Library For Example: class Staff : public Employee { … } class Visitor : public Person { … } class Transfer : public Student { … } Previous LIST Code Works without Modification Application that Creates Person Instances May Need to be Modified and Recompiled
82
Generics Classic Programming Problem
Develop Stack or List Code in C that Applies to a Single Type (e.g., List of DeliItems) Need Same Code for ProduceItems, MeatItems, etc., Copy and Edit Original Code Minimal Reuse, Error Prone, Time Consuming What do Generics Offer? A Type-Parameterizable Class Abstracts Similar Behavior into a Common Interface Reusable and Consistent Class Illustrate via C++
83
A Generic Stack Class template <class T> stack { private: T* st,
int top; int size; public: void stack(int x) {st = new T[x]; top = 0; size = x;} stack() {st = new T[100]; top = 0; size = 100;} ~stack() {delete st;} push(T entry) { st[top++] = entry;} }; main() { stack<int> S1(10); // Creates int Stack with 10 Slots stack<char> S2; // Creates char Stack with 100 Slots stack<Item> ItemDB(10000); // Stack of Grocery Items }
84
A Generic Set Class template <class ItemType> class Set {
DLList<ItemType>* _members; // Set Templates Uses Double-Linked List Template public: Set() { _members = new DLList<ItemType>(); } void Add(ItemType* member) {_members->queue(member);} void Remove(ItemType* member) {_members->remove(member);} int Member(ItemType* member) {return _members->isMember(member);} int NullSet(){return _members->isEmpty();} } main() { Set<int> IntSet; // Creates an Integer Set Set<Item> ItemDB; // Creates an Item Set }
85
Benefits of Generics Strong Promotion of Reuse Develop Once, Use Often
stack and Set Examples Eliminate Errors and Inconsistencies Between Similar and Separate Classes Simplifies Maintenance Problems Focuses on Abstraction and Design Promotes Correctness and Consistent Program Behavior Once Designed/Developed, Reused with Consistent Results If Problems, Corrections in Single Location
86
Important Comment on Typing Issues
Consider the Four Features of Subtyping: Substitutability: If B IS A, then B Can Occur where A is Expected. Static-Type Checking: Everything is Known at Compile Time Mutability: An Instance Changes Type at Run Time Specialization via Constraints: Allows the Further Restrictions of Instance Characteristics via Inheritance Claim: Only Three of Four Can Ever Exist in a Single Model!
87
Substitutability Recall that Employee is a Subclass of Person
Substitutability Allows Employee to be Utilized in any Context that Person is Permitted Implications of Substitutability P and E Variables of Person and Employee Assignment: P = E; Parameter Passing: If P is the type of a Parameter, E can be Substituted in its Place Polymorphism/Dispatching Allows Faculty, Grad, and UnderGrad to Substitute for Person NonPItem, DeliItem, DairyItem, etc., to Substitute for Item
88
Mutability Mutability Allows an Instance to Dynamically Change its Type within an Executing Application Excellent Conceptual Example from CAD Consider Boxes and Thru-Hole As Thru-Hole Moves Does Its Type Change? Does it Become a Blind Hole? Does it Alter its Depth to be a Thru-Hole? Muting a Powerful Concept that Breaks Rules
89
Other Features Static Type Checking – Compilation All Types Known
All Decisions Made Specialization via Constraints Only Three out of Four Can Co-Exist…. Adding Fourth Causes Contradiction… Person Faculty Student(BS/MS/PHD) Undergrad (BS) Graduate (MS/PHD)
90
How Does Contradiction Occur?
Specialization via Constraints with Set_Degree Method (see Previous Slide) Assume Static TC, Substitutability, and Mutability Suppose: Var S: Student; U: Undergrad; S := U; // OK if Subst. and Mutab. Set_Degree (S, MS); //No Compile Error Runtime: Unless Static TC Weakend, the Wrong Set_Degree Operation will be Chosen
91
An Overview of Java Java is a Third Generation, General Purpose, Platform Independent, Concurrent, Class-Based, Object-Oriented Language and Environment Java Composed of JDK and JRE Java Language Java Packages (Libraries) javac Compiler to Bytecode (p-code) JDB Java Debugger Java Interpreter - Platform Specific JDK: Java Development Environment JRE: Java Runtime Environment
92
Java and New Technologies (Mobile)
93
Packages In Java Allows Related Classes to be Grouped into a Larger Abstraction Similar to Ada95 Packages Unavailable in C++ Utilization of Packages for SW Design and Development Components, Modularization, Groupings Enforcement by Compiler of Package Rules Overall, Packages Enhance the Control and Visibility to Fine-Tune Who Can See What When
94
The Java Language Overview of Non-OO Capabilities Based on C/C++
No includes, typedefs, structures, groups Unicode Character Set - 34,168 Characters Automatic Coercions Not Supported Strongly-Type Language Variables in Java Primitive Types: ints, floats, booleans, Unicode chars Reference Types: arrays, classes, interfaces No Physical Pointers in Java!
95
The Java Language Statements in Java - Resembles C and C++
Assignment/Expressions and Precedence for, while, do-while if-then, switch-case break, continue, label, return Exception Handling Similar to C++ try, throws, catch Blocks Strongly Integrated Throughout APIs
96
The Java Language Motivating the Class Concept
Conceptually, Classes are Structures/Records with Functions that are Encapsulated structure Item { int UPC, OnShelf, InStock, ROLimit; char* Name; float RCost, WCost; Status Create_New_Item(int UPC, ...); NameCost* Get_Item_NameCost(int UPC); void Modify_Inventory(int UPC, int Delta) ; Boolean Check_If_On_Shelf(int UPC); Boolean Time_To_Reorder(int UPC); }; NameCost *nc; Item I1, I2; I1.Create_New_Item(...); nc = I2.Get_Item_NameCost(UPC);
97
The Java Language Object-Oriented Features
Class - similar to C++ Class Classes have Members (Methods and Variables) Members Tagged Using Keywords private: Typically, Inaccessible public: Potential to be Accessible protected: Accessible via Inheritance package: Accessible within Package Involve Visible Between Classes, Within Packages, and Due to Inheritance
98
Classes in Java A Supermarket Item
Keywords must be Utilized for Each Attribute or Method Declaration class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost; public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta){...}; public int Get_InStock_Amt() {return Quantity;}; };
99
Classes in Java class Item { private String UPC, Name;
private int Quantity; private double RetailCost; protected double WholeCost; public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta) { int i = Get_InStock_Amt (); if (Delta >= 0) { Quantity += Delta; return true; } else { return false;} }; public int Get_InStock_Amt() {return Quantity;}; public double Compute_Item_Profit() {...}; protected boolean Modify_WholeSale(); {...}; };
100
Visibility of Attributes/Methods
Class Members (Attributes and Methods) Visibility Tags for Members Private: Visible only to Class Protected: Visible to Class and Other Classes within Package Public: Visible to Class, Other Classes within Package, and if Class is Public, Visible to Other Packages/Classes No Tag: Visible Only to Other Classes within Defining Package Java's Controlled Sharing within/between Packages not Supported in C++ Abstraction/Encapsulation Superior in Java!
101
Inheritance - Two Roles
Controlled Sharing Between Classes Generalization vs. Specialization Treat Instances of Different Classes in a Uniform Fashion Polymorphism and Dynamic Binding Inheritance in Java Item / \ DeliItem ProduceItem | SaladItem class DeliItem extends Item { ... }; class SaladItem extends DeliItem { ... }; class ProduceItem extends Item { ... };
102
Designing and Developing Java Classes
Encapsulation Capabilities of Java Classes (Data + Operations) - ADTs Packages - Collections of “Related” Classes Class Declaration: Access Modes and Variable Members Constructors and Class Bodies Method Declaration and Access Modes Class and Instance Members Garbage Collection
103
Class Definition Class Declaration Member Variable Constructors
public class Stack { private Vector items; public Stack() { items = new Vector(10); } public Stack(int numElem) { items = new Vector(numElem); public Object push(Object item) { item.addElement(item); return item; public synchronized Object pop() { int len = items.size(); Object obj = null; if (len == 0) throw new EmptyStackException(); obj = items.elementAt(len - 1); items.removeElementAt(len - 1); return obj; public boolean isEmpty() { if (items.size() == 0) return true; else return false; Class Declaration Member Variable Constructors Class Body Member Methods
104
Packages A package is a Collection of Related Classes and Interfaces that Provides Access Protection and Namespace Management File Name and Package Name Identical Packages are Imported via the import Keyword package graphics; class Circle extend Graphic implements Draggable { ... } class Rectangle extends Graphic implements Draggable interface Draggable {
105
Access Modes Constructors and Members can be defined as:
public: Any other class can invoke them. protected: Only subclasses and classes in the same package can invoke them. private: Only accessible within the class. package: Accessible only to other classes and interfaces declared in the same package (default if omitted). Controls Encapsulation and Allows Evolvability with Minimal Impact on other Classes that use the Members Deciding Appropriate Access Mode Determines Security and Ensures that Data Remains in a Consistent State.
106
Constructors Utilized to Create a new Class instance by Reserving Sspace for the Member Variables Rectangle rect = new Rectangle(); Member Variable Initialization Possible Constructors Mimic Class Name with No Return Type Default Constructor with Empty Argument List Constructors may be Overloaded
107
Variable Members Declaration (Class Body)
Defines the Type of a Variable Instantiation (Constructor) Reserves Memory for the New Instance Initialization Assign Initial Value(s)
108
Method Members Declaration Access Level Return Type Name Arguments
public, protected, private, or package Return Type void or type return statement Either return the declared type or a subtype Name Overloading Overriding Arguments List of variable declarations Cannot include methods Argument names may hide member names: this
109
Method Members (cont.)
110
Example public class Point { public int x = 0; public int y = 0;
public void move(int newX, int newY) { x = newX; y = newY; } public class Line { public Point origin; public Point end; public Line() { origin = new Point(); end = new Point(); public Line(Point origin, Point end) { this.origin = origin; this.end = end; aLineObject Default Constructor Line Instance origin end x y x y Point Instances Overloading Hiding
111
Class and Instance Members
Class Members are Defined with the Keyword static Class Variables and Class Methods are Associated with the Class Rather than each of its Instances Class Variables are Shared Among all Instances JRE Creates one copy of Class Variables the First Time it Encounters a Containing Instance Class Methods only Operate on Class Variables Class Bariables declared as final are constants Class Members are Accessible without the need to Instantiate the Class className.classMethod(); className.classVar = 10;
112
Class and Instance Members (Continued)
class AnInteger { int x; public int x() { return x; } public void setX(int newX) { x = newX; class AnInteger { int x; static public int x() { return x; } static public void setX(int newX){ x = newX; class AnInteger { static int x; public int x() { return x; } public void setX(int newX) { x = newX; … AnInteger myX = new AnInteger(); AnInteger yourX = new AnInteger(); myX.setX(1); yourX.x = 2; System.out.println(“myX = “ + myX.x()); System.out.println(“yourX = “ + yourX.x());
113
Garbage Collection Unreferenced Objects are Garbage Collected Automatically Memory is Freed for Later Reuse Garbage Collection runs in a Low Priority Thread, either Synchronously or Asynchronously The finalize() Method is Inherited from Object and can be Overridden to Liberate Resources
114
Inheritance in Java Basic Definitions and Concepts
Generalization vs. Specialization Subclass vs. Superclass Acquisition Rules What Does Superclass Pass to Subclass? What Does Subclass Inherit from Superclass? What is Visible within Packages? Overriding vs. Overloading? Role of Public, Final, and Abstract Classes Java Interfaces for Design-Level Multiple Inheritance and Quasi Generics
115
Inheritance - Terms and Concepts
Every Class in Java is Derived from the Object Class Java Classes can be Organized into Hierarchies Using the extends Keyword Establishing Superclass/Subclass Relationships Between the Classes in Application A Superclass Contains Members Common to Its Subclasses - Generalization Subclasses Contain Members Different from Shared Superclass - Specialization Only Single Inheritance is Supported in Java at Implementation Level!
116
Subclass & Superclass Subclass
Subclass is a Class that Extends Another Class Inherits State and Behavior from all of its Ancestors Subclass can use the Inherited Member Variables and Functions or hide the Inherited Member Variables and Override the Inherited Member Functions Superclass Superclass is a Class’s Direct Ancestor
117
A Superclass in Java A Supermarket Item
Keywords must be Utilized for Each Attribute or Method Declaration class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost; public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta){...}; public int Get_InStock_Amt() {return Quantity;}; };
118
Inheritance - Defining Subclasses in Java
Item / \ DeliItem ProduceItem | SaladItem class DeliItem extends Item { ... }; class SaladItem extends DeliItem { ... }; class ProduceItem extends Item { ... };
119
Members Inherited By a Subclass
Subclass Inherits all Public/Protected Members of a Superclass DeliItem Inherits Public/Protected from Item Subclass Inherits all Package Members of Classes in the same Package as the Subclass All superclass Members can be Declared with no Access Specification, if Subclass is in the Same Package as the Superclass
120
Members Not Inherited By A Subclass
Subclass does not Inherit Private Members of a Superclass DeliItem doesn’t Inherit Private from Item Subclasses do not Inherit a Superclass’s Member if the Subclass Declares a Member with Same Name Member Variables - Subclass Hides the Member Variable of the Superclass Member Methods - Subclass Overrides the one in the Superclass
121
Hiding Member Variables and Overriding Member Methods
class parentClass { boolean state; void setState() { state = true; } class childClass extends parentClass { state = false; super.setState(); System.out.println(state); System.out.println(super.state)
122
Overriding Member Methods
Subclasses CANNOT Override Methods that are Declared to be Final in the Superclass Subclasses MUST Override Methods that are Declared as Abstract in the Superclass Subclasses MUST be Declared as Abstract if they do not Override Abstract Methods from the Superclass
123
Methods Inherited From Object Class
The Java “Object” Class Defines Basic State and Behavior of all Classes and Their Instances User Defined Classes can Override these Methods: clone equals finalize toString hashCode User Defined Classes Cannot Override: getClass notify notifyAll wait
124
Public, Final, and Abstract Classes
Public Classes Within Package, public Classes Become Visible to Outside World Public Members are Exported Final Classes Prohibits Subclassing for Security Final Class Prevents Access of Protected Members via Subclassing Not Supported in C++/Ada95 Abstract Classes Can't be Instantiated No Implementations for Abstract Methods
125
Final Classes and the “Final” Keyword
A Class is Declared as Final - the Class Cannot be Subclassed. For Security For Design A Method is Declared as Final in a Class - any Subclass Cannot Override that Method A Variable is Declared as Final - the Variable is a Constant and it Cannot be Changed
126
Abstract Classes And Methods
Cannot be Instantiated Can only be Subclassed Keyword “abstract” before Keyword “class” is used to Define an Abstract Class Example of an Abstract Class is Number in the java.lang Package Abstract Methods Abstract Classes may contain Abstract Methods This allows an Abstract Class to Provide all its Subclasses with the Method Declarations for all the Methods
127
A Sample Abstract Class
abstract class Item { protected String UPC, Name; protected int Quantity; protected double RetailCost, WholeCost; public Item() { ... }; abstract public void finalize(); abstract public boolean Modify_Inventory(int Delta); public int Get_InStock_Amt() {...}; public double Compute_Item_Profit() {...}; protected boolean Modify_WholeSale(double NewPrice);{...}; };
128
Another Abstract Class and Methods
abstract class GraphicsObject{ int x, y; void moveTo(int x1,y1) { } abstract void draw(); } class Circle extends GraphicsObject{ void draw() { } class Rectangle extends GraphicsObject{
129
Interfaces in Java Design-Level Multiple Inheritance Java Interface
Set of Methods (no Implementations) Set (Possibly Empty) of Constant Values Interfaces Utilized Extensively Throughout Java APIs to Acquire and Pass on Functionality Threads in Java - Multiple Concurrent Tasks Subclassing from Thread Class (java.lang API) Implementing an Interface of Runnable Class
130
A Sample Interface in Java
Teaching Student Employee / \ | UnderGrad Graduate Faculty interface Teaching { int NUMSTUDENTS = 25; void recordgrade(Undergrad u, int score); void advise(Undergrad u); ... etc ... } class Graduate extends Student implements Teaching{ ...} class Faculty extends Employee implements Teaching{ recordgrade() Different for Graduate & Faculty
131
Quasi Generics in Java class Set implements Coll{
void add(Object obj){ ... } void delete(Object obj){ } interface Coll { int MAXIMUM = 500; void add(Object obj); void delete(Object obj); Object find(Object obj); int currentCount(); } class Queue implements Coll{ void add(Object obj){ ... } void delete(Object obj){ }
132
Polymorphism and Object Serialization in Java
Polymorphism via Dispatching Allows a Runtime or Dynamic Choice of the Method to be Called based on the Class Type of the Invoking Instance Promotes Reuse and Evolution of Code Polymorphism/Dispatching Incurs Cost or Overhead at both Compile and Runtime! Serialization Conversion of Object to Format that Facilitates Storage to File or Transfer Across Network Process Controlled via API with Minimal Interaction by Software Engineer
133
Polymorphism Substitutability
Whenever Value of a Certain Type is Expected, a Subtype can also be Provided In Context of Inheritance, All Subclasses can be Treated as Common Root Class Simplifies Code and Facilitates Reuse Static Type Type Defined in the Variable Declaration Dynamic Type Type of the Actual Value held by the Variable at Runtime
134
Polymorphism A Variable is Polymorphic Whenever it may have Different Static and Dynamic Types Static Variable I1 Defined with Type Item Dynamic Variable Access Allows I1.Print() to be Invoked on DeliItem, ProduceItem, etc., Instances Problems: Reverse Polymorphism: Can we get the Subtype Variable Back After Assigning its Value to a Supertype? Method Binding: When Invoking a Method on a Variable, should it be Selected According to its Static or Dynamic Type?
135
An Example We have a class Ball, and two subclasses WhiteBall and BlackBall The SelectOne() method gets a WhiteBall and a BlackBall as arguments and returns one of them selected randomly Questions: What is SelectOne()’s return type? How can we know which ball was returned? SelectOne ?
136
Dynamic Binding and Casting
The static type of b is Ball, but its dynamic type is either WhiteBall or BlackBall. public class Ball { public String id = new String("I'm a ball"); public String GetId() { return id; } public class WhiteBall extends Ball { public String id = new String("I'm white"); public void OnlyWhite() { System.out.println("Yes, I'm white"); public class BlackBall extends Ball { public String id = new String("I'm black"); public void OnlyBlack() { System.out.println("Yes, I'm black"); class balls { public static void main(String[] args) { WhiteBall wb = new WhiteBall(); BlackBall bb = new BlackBall(); Ball b = SelectOne(wb, bb); System.out.println(b.GetId()); System.out.println(b.id); if (b instanceof WhiteBall) { wb = (WhiteBall)b; wb.OnlyWhite(); } else { bb = (BlackBall)b; bb.OnlyBlack(); } public static Ball SelectOne(WhiteBall w, BlackBall b) { if (Math.random() > 0.5) return w; else return b; What is going to be printed?
137
Class Student (Superclass) - Maintains Student Information
public class Student { // protected used to facilitate inheritance protected String name, SSN; protected float gpa; // constructor used to initialize object public Student(String n, String ssn,float g) { name = n; SSN = ssn; gpa = g; } public String getName() { return name; } public float getGpa() { return gpa; } public String getSSN() { return SSN; } // diplay student information public void print() { System.out.println("Student name: " + name); System.out.println(" SSN: " + SSN); System.out.println(" gpa: " + gpa); }
138
Class Grad public class Grad extends Student { private String thesis;
public Grad(String name, String ssn, float gpa, String t) // call parent's constructor super(name, ssn, gpa); thesis = t; } public String getThesis() { return thesis; } public void print() super.print(); System.out.println(" thesis: " + thesis);
139
Class Undergrad public class Undergrad extends Student {
private String advisor; private String major; public Undergrad(String name, String ssn, float gpa, String adv, String maj){ super(name, ssn, gpa); advisor = adv; major = maj; } public String getAdvisor() { return advisor; } public String getMajor() { return major; } public void print() { super.print(); System.out.println(" advisor: " + advisor); System.out.println(" major: " + major);
140
Class StudentDB import java.util.Vector; public class StudentDB{
private Vector stuList; // constructor public StudentDB(int size){ // allocate memory for vector stuList = new Vector(size); } // returns number of students stored public int numOfStudents() { return (stuList.size()); } public void insert(Student s) { stuList.addElement(s); } // search for student by name public Student findByName(String name){ Student stu = null; // temp student boolean found = false; int count = 0; int DBSize = stuList.size(); while ((count < DBSize)||(found == false)){ stu = (Student) stuList.elementAt(count); if (stu.getName().equals(name)) found = true; count++; } return stu;
141
Class StudentDB (Continued)
public Student remove(String name) { Student stu = null; // temp student boolean found = false; int count = 0; int DBSize = stuList.size(); while ((count < DBSize) || (found == false)){ stu = (Student) stuList.elementAt(count); if (stu.getName().equals(name)) found = true; count++; } if (found == true) stuList.removeElementAt(count - 1); return stu; public void displayAll() { int DBSize = stuList.size(); for (int i = 0; i < DBSize; i++) Student stu = (Student) stuList.elementAt(i); stu.print(); System.out.println(); }
142
Class MainInterface public class MainInterface { private StudentDB db;
public static void main(String[] args) { MainInterface studentInt = new MainInterface(); studentInt.displayMenu(); } // constructor public MainInterface() { db = new StudentDB(5); public void displayMenu(){ int option = 0; System.out.println("\n 1. Insert "); System.out.println(" 2. Delete "); System.out.println(" 3. Search "); System.out.println(" 4. Display "); System.out.println(" 5. Exit \n"); option = Console.readInt("Enter your choice: "); while (option > 0 && option < 5) { processOption(option); System.out.println(" 2. Delete"); option = Console.readInt("Enter your choice: "); } }
143
Class MainInterface (Continued)
public void processOption(int option) { String name, SSN; float gpa; switch (option){ case 1: int type = Console.readInt("1. Grad or 2. Undergrad? "); name = Console.readString(“Name: "); SSN = Console.readString(“SSN: "); gpa = (float) Console.readDouble("gpa: "); if (type == 1){ String thesis = Console.readString("Enter thesis title:"); Student g = new Grad(name, SSN, gpa, thesis); db.insert(g); }
144
Class MainInterface (Continued)
else{ String advisor = Console.readString("Enter advisor:"); String major = Console.readString("Enter major: "); Student u = new Undergrad(name, SSN, gpa, advisor, major); db.insert(u); } break; case 2: name = Console.readString(”Name"); Student s = db.remove(name); s.print();
145
Class MainInterface (Continued)
case 3: name = Console.readString("Enter name: "); Student stu = db.findByName(name); System.out.println(); stu.print(); break; case 4: db.displayAll(); }
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.