1 / 52

Introduction to Classification

Introduction to Classification. So What’s a Class, Anyway?. A class is a type and as such is a partial or full implementation of an Abstract Data Type A class is a general description of objects from a specific problem domain that share identical semantics and attributes

cholloway
Télécharger la présentation

Introduction to Classification

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

E N D

Presentation Transcript


  1. Introduction to Classification

  2. So What’s a Class, Anyway? • A class is a type and as such is a partial or full implementation of an Abstract Data Type • A class is a general description of objects from a specific problem domain that share identical semantics and attributes • A class is a collection of related subroutines packaged together, along with a definition of the data that the subroutines manipulate or use (Cockburn paraphrased) • A class is a software construct describing an abstraction drawn from a problem domain and optionally, its implementation.

  3. Classes Concepts • In OO, a Class is the central unit of modularization • Every class defines a new type. A class may or may not define an implementation of its semantics (provide a full implementation of its methods). A class which does not provide a full implementation is called an Abstract Class. • In OO, classification is the process of creating a new language drawn from a particular problem domain. • A class is an ADT that defines behavior in terms of methods and state in terms of attributes

  4. Classes Concepts • A Class conceptualizes the data and function necessary to implement a subset of user requirements • A Class is “the descriptor for a set of objects that share the same attributes, operations, relationships, and behavior.”—Rumbaugh • A Class is a set of objects that share a common structure and a common behavior (protocol).—Booch • A well-designed Class provides a crisp abstraction of some thing drawn from the vocabulary of the problem domain or the solution domain.—Booch

  5. … from a specific Problem Domain • Insurance: Claim, Policy, Bill, Provider, Coverage, Obligation • Accounting: Invoice, Payment, Interest, Check, AutomatedPayment • Banking: Customer, Account, CheckingAccount, SavingsAccount • Air Traffic Control System: Plane, Airport, Alarm • University Registration System: Student, Instructor, Course, Section

  6. Classes Encapsulate State and Behavior • Behavior is encapsulated in the code necessary to the conduct the fulfillment of some set of requirements defined for a class of things • State is the data that are necessary for the individualization of the class instance in fulfilling its requirements • A class satisfies the requirements of a given abstraction defined in a given problem domain

  7. Behavior Fundamentals • Behavior is implemented by defining operations on a class of things • Behavior defines the implementation for the requirements of a class • Instances of a Class can be treated in the same way: • All Policies can be renewed and cancelled • All Accounts can be opened and closed • All Checks can be issued and deposited • All Payments can be processed and credited • All Planes can descend and land • All Trades can be executed and validated

  8. State Fundamentals • State is implemented by defining Attributes on a class of things (and also relationships—but later) • State is the place in a Class definition where the individualization of a particular instance of a class is stored • An Account’s balance and number • A Trade’s execution price and date • A Plane’s altitude and speed • A Policy’s premium and beneficiary • A Course’s number of students enrolled

  9. What is defined for a Class? • State (encapsulated as Attributes in UML) • Behavior (encapsulated as Operations in UML) Class Name State Behavior

  10. Java Student public class Student//CLASSNAME { //STATE: String student_name; int student_ID; //BEHAVIOR: public boolean registerForClass() { … } public boolean dropClass() { … } public boolean save() { … } public boolean modify() { … } public boolean load() { … } }

  11. Methods • There may be various ways in which an operation may be implemented. • These various ways are the methods by which a given requirement may be implemented • These methods may be encapsulated as implementations of a common operation defined in the Class’s interface There may be various methods by which the encrypt operation may be implemented (DES, RSA, Blowfish, etc)

  12. Synonyms I • The Class’s Operations are sometimes called: • Protocol • Behavior • Interface (Java) • API • Services • Methods (Java) • Member functions

  13. Synonyms II • The Class’s Attributes are sometimes called: • State • Member variables (Java) • Instance variables (Java) • Class variables (Static variables, Java)

  14. Mommy, Where Do Objects Come From? • If Classes, as Kant says, come from your brain, where do Objects come from? • Classes as blueprints or molds (C++ motivation) • Creepy Crawlers ThingMaker by Mattel • Constructors • Destructors (in non-garbage-collected languages) • Classes as factories (Smalltalk motivation) • In Java, we create new classes using the new keyword

  15. Constructors • A constructor is a method on a class that has no return type and is usually public • A constructor is called during the process of object construction/instantiation • A default constructor (a constructor with 0 parameters) will be automatically created for your class if you do not define one yourself • Example: java ReflectionTest BasicClass • The default constructor sets all instance variables to the following defaults: • numerics to 0 • booleans to false • object references to null

  16. Rules for Constructors • A constructor has the same name as the class • A class can have more than one constructor • A constructor can take any number of parameters, including 0 • A constructor cannot have a return type (the implied return type is an instance of the class itself) • A constructor is always called by the new operator (because all Java objects are created on the heap)

  17. Object Construction • When new is called, the compiler will look through the list of constructors, and try to find a constructor that matches the parameters passed in the new command: MyObject mo = new MyObject(1,”hi”, true); • would match: public MyObject(int x, String s, boolean b) {…} • One constructor can call another (for code reuse) by using the following syntax: • this(1,”hi”,true); //calls the above constructor in blue • Example: ObjectConstruction1.java, ObjectConstruction2.java, ObjectConstruction3.java, ObjectConstruction4.java (construction blocks)

  18. Factories • Factories are objects that create other objects on request • Factories can hide the class of an object from the requester, delivering a generic type back which the client can then use polymorphically and ignorantly of the actual class (eg: A “Window” object with varying look and feel) • Sometimes you don’t want the client choosing the type of object to create—you want to hide new • By encapsulating object creation in a factory, when a new type is added, only the factory needs to be modified • We can also define Factories in Java, but more of that later when we discuss patterns

  19. Class Attributes (Static Fields) • Attributes that belong to a class of things are called Class Attributes • Often called “static” as in static variable and static method • A Class Attribute is shared among all runtime instances of a given class • Examples: • Count of items on a Stack • Totals

  20. Class Methods (Static Methods) • A Class Method (or static function) is a method defined for a class that belongs to the class and not to an individual instance • This means that no object needs to be present in order for the method to be called—the method is called on the class • There is no inherent this pointer associated with a class method (therefore class methods can only access class variables) • Class methods cannot be called polymorphically • Class methods are used primarily as encapsulated methods for Class attributes • Example: ClassMethod.java, BrokenClass.java

  21. Member Visibility (applies to both variables and methods) • Classes may have certain protection mechanisms that determine the degree of visibility any given attribute or operation may have: • public (visible to ANY OTHER OBJECT) • private (visible ONLY to instances of THIS class) • protected (visible ONLY to instances of THIS class AND its derivatives) • package (visible ONLY to instances of THIS class AND instances of other classes IN THE SAME PACKAGE)

  22. Member Visibility • In generally, you encapsulate data in Java by declaring member variables private • You then provide public accessor methods for instances of other classes to access that private data • Accessor methods “return” private data as copies, they do NOT return references or pointers to the actual private data member • If you need to offer a way for others to changeprivate data, use a publicmutator method • Example: MemberVisibility.java0

  23. Encapsulation Revisited • Modular motivation: Hiding the implementation from the client • Less dependence on particular implementations • fewer assumptions by the client • clients can only manipulate encapsulated entities, not the internals • since clients can only interact through defined interfaces (methods), the implementation can change without affecting the clients • Encapsulation provides limited and controlled access to an object’s state, through public, protected, and private methods.

  24. So What’s an Object? • A run-time named instance of a Class with a unique identity • An object is not a Class. Do not confuse the mold with the product, the blueprint with the house • An object has individual state, behavior, and identity. (Booch) • An object is an instance of a Class, similar to the way a variable is an instance of a data type in a programming language • An object exists only in computer memory, a Class exists in your mind and in your design

  25. Classes and Instances • An object is an instance of a class when it has a name and an address (reference). • Examples: • Class: Flight Instance (object): TWA 2345 on 08/15/2000 • Class: Employee Instance (object): Bob Smith, SSN 123-45-6789 • Class: Date Instance (object): 08/15/2000 • Class: Account Instance (object): Wilma Meyers, balance $123.80

  26. Object-Object Communication • Objects communicate by sending messages to other objects • These messages are part of the defined interface of the other class • An object must have an implementation of every operation defined in its interface

  27. Abstract Classes • Abstract Classes are types that cannot be instantiated, but represent an abstraction from other classes and serve to encapsulate common class interfaces or behavior or both • Apples, Oranges, Pears, and Avocados are types of Fruit: • But what does “a fruit” taste like? • How many calories are in “a fruit”? • How much does “a fruit” cost? • Waiter: What you like for dinner, Sir? • Customer: I’d like an appetizer, an entrée, and a dessert.

  28. Abstract Classes • Shape s; meaningless—a “shapeless” shape • An Abstract Class is: • a class that does not know how to instantiate itself • a class that therefore cannot be instantiated • a class that may include a partial implementation of its semantics (methods)

  29. Basic Interfaces

  30. Interface and Implementation • Operations defined for a Class represent that Class’s interface (sc. to user’s of the Class) • It’s the language other classes use to communicate with the Class • For any given operation, code may be defined as the method by which a requirement is accomplished • In some languages (like Java), an operation is called a method • Always remember that a method’s {implementation} is one method by which a requirement is accomplished, among other methods • “What method do you use to …?”

  31. Interface Abstraction

  32. What is an Java interface? • Like a class but contains only abstract methods and final variables example: interface FooInterface{ void foo1(); int foo2(double x); } abstract interface FooInterface{ public abstract void foo1(); public abstract int foo2(double x); } Both are correct! the abstract and public keywords are implied, so the shorthand is recommended.

  33. Interfaces, cont. • Unlike a class, an interface cannot be instantiated (whatever would foo1() do when called???)! • Rather, an interface is implemented by some other class: class FooImplementation implements FooInterface{ .... } • This means one thing only: FooClass must contain versions of both the methods foo1 and foo2 that actually do something. We say that FooImplementation must provide implementations for all of the methods in FooInterface.

  34. ANDREW: • We did not get any further than this.

  35. Interfaces, cont. • When a class implements an interface, think of the class as entering a contract to provide meat for all methods in the interface—think of it as a deal between the programmer and the compiler • The compiler will check that this contract is adhered to • Otherwise, the class implementing the interface can contain anything else that a regular class contains • Again: do not try to instantiate an interface—this is meaningless!

  36. Extending interfaces • An interface may also extend other interfaces • Example:interface FooInterface{ int foo1(); } interface FooInterface2 extends FooInterface{ int foo2(); } • FooInerface2 inherits method foo1 and declares foo2 • Anything that contracts to implement FooInterface2 must implement both foo1 and foo2 • Example: FooInterfaceTest.java

  37. How interfaces are used • This is difficult because there is no single, simple answer to the question. • Like any semantic feature in a programming language, there are no hard and fast rules about in what situations it should best be exploited. • However, there are many guidelines and general strategies (or else the feature would have never bee included). • We’ll cover a few ways in which interfaces are typically used.

  38. Some interface uses • To simply clarify the the functionality associated with a particular abstraction • To abstract functionality in a method to make it more general, such as pointers to functions are used in C. sort is a good example. • To implement callbacks, such as in GUI programming • To write more general, implementation depending code that is easy to extend and maintain. • To simulate global constants.

  39. Composition and Delegation

  40. Composition: Another Form of Reuse • Composition is another form of reuse • Instead of reusing capabilities by inheriting operations from a base class (which implies a taxonomic relationship), you embed a reference to another class within your class, and delegate out to (reuse) operations defined by the other class

  41. Differences between Inheritance and Composition • The composing class publishes the composed class’s interface, and simply delegates out to the composed class for implementations • Composition per se does not imply a taxonomic relationship between classes (an AeleronController is not a type of AltitudeController)

  42. Dynamic Determination • Composition is more flexible than inheritance because method implementations can be dynamically selectable (determined) at runtime

  43. Characteristics of Composition • Composition models a has-a relationship, as opposed to Inheritance which models an is-a relationship • Composition is a strengthened form of aggregation implying simultaneous lifetimes • Square and its four sides • DerivedClass and its radius • hand and its fingers (robotics) • Strong Composition implies: • a part cannot belong to more than one whole (that’s my reference, dear) • concurrent instantiation and destruction with whole

  44. Composition and Attribution • Attributes of a class can either be simple (domain valued) or relational (delegatory) • An Employee may have a classification code: either hourly or salaried • Which is “correct”?

  45. Heuristics • Might classification codes themselves participate in a hierarchy? For instance, is an person earning commission a type of salaried employee? (=relational) • Is the set of domain values predefined and not subject to change? Ie., regulatory mandated (=simple) • Might you need to add a new classification code? (=relational) • Would you ever need to individually manipulate (totalize, count, etc.) all salaried employees? (=relational) • Do classification codes themselves have attributes (rates, etc.)? (=relational)

  46. Design Heuristics • Prefer composition over inheritance except when: • a clear hierarchy of types exists within the Problem Domain itself, and this hierarchy is never expected to change • Defined roles exist that are never expected to change within a given Problem Domain

  47. Java Packaging • Java packages allow you to group together related classes and specify particular namespaces in order to prevent class name collisions (e.g., java.util.Date and java.sql.Date) • Java.lang package is imported by default—no need to specify • Class Importation • import java.util.Date; • import java.util.Vector; • Static Imports (Java 1.5) • import static java.lang.System.*; //… • Out.println(“Hello World”) //instead of: • System.out.println(“Hello World”); • Example: MyClass.java

  48. Using classes from a package • Two ways to access classes from a package: • use full package name: • java.util.ArrayList x = new java.util.ArrayList(); • use a class-specific import statement: • import java.util.ArrayList • then can use just class name everywhere after import • What if names conflict? • compiler warning • must use full name to distinguish or import exact class name or a class-specific import statement • Can also use wildcard for all classes in package • import java.util.*;

  49. Creating packages • To create a package, place the package identifier at the top of your source code. e.g. package myjava.classes; • This places the current class/classes in a package called myjava.classes (notice the lowercase convention for package names). • Important: this class must be placed in a corresponding directory structure under [$ROOT]/myjava/classes. • Your CLASSPATH must contain [$ROOT]

  50. Class visibility • Classes themselves can be public or default (We’ll talk about inner classes later) public class Foo{ ...} //public access class Foo{ ... } //default—package access • Classes that are public are visible outside of their package—that’s what we mean by public • Classes that are default are visible only within their package • Every source code file can have at most one public class (which it’s named after) but any number of package-scope classes.

More Related