Introduction to Classification. So What’s a Class, Anyway? A class is a type and as such is a...

52
Introduction to Classification
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    222
  • download

    0

Transcript of Introduction to Classification. So What’s a Class, Anyway? A class is a type and as such is a...

Page 1: 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.

Introduction to Classification

Page 2: 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.

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.

Page 3: 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.

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

Page 4: 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.

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

Page 5: 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.

… 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

Page 6: 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.

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

Page 7: 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.

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

Page 8: 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.

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

Page 9: 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.

What is defined for a Class?

• State (encapsulated as Attributes in UML)• Behavior (encapsulated as Operations in UML)

Student

namestudentID

registerForClass()dropClass()save()modify()load()

Class Name

State

Behavior

Page 10: 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.

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() { … }

}

Page 11: 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.

Methods

There may be various methodsby which the encrypt operation may

be implemented (DES, RSA, Blowfish, etc)

Encryptor

<<dynamic>> AlgorithmImpl

setImplementation()encrypt()

• 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

Page 12: 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.

Synonyms I

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

Page 13: 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.

Synonyms II

• The Class’s Attributes are sometimes called:– State– Member variables (Java)– Instance variables (Java)– Class variables (Static variables, Java)

Page 14: 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.

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

Page 15: 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.

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

Page 16: 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.

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)

Page 17: 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.

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)

Page 18: 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.

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

Page 19: 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.

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

Page 20: 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.

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

Page 21: 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.

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)

Page 22: 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.

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 change private data, use a public mutator method

• Example: MemberVisibility.java0

Page 23: 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.

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.

Page 24: 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.

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

Page 25: 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.

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

Page 26: 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.

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

WindowDialogBox

displayYourself()

displayYourself

Here is one implementation of the displayYourself operation

Page 27: 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.

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.

Page 28: 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.

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)

Fruit

getTaste()isTart()

Apple Banana Pear Kiwi

Page 29: 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.

Basic Interfaces

Page 30: 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.

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 …?”

Page 31: 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.

Interface Abstraction

Page 32: 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.

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 publickeywords are implied,so the shorthand is recommended.

Page 33: 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.

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.

Page 34: 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.

ANDREW:

• We did not get any further than this.

Page 35: 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.

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!

Page 36: 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.

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

Page 37: 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.

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.

Page 38: 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.

Some interface uses

1. To simply clarify the the functionality associated with a particular abstraction

2. 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.

3. To implement callbacks, such as in GUI programming

4. To write more general, implementation depending code that is easy to extend and maintain.

5. To simulate global constants.

Page 39: 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.

Composition and Delegation

Page 40: 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.

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

for subtle alititude increases, adjust the aeleron

AltitudeController.climb() delegates out to (calls on) AeleronController.increment()

AltitudeController

climb()

AeleronController

increment(degrees)

Page 41: 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.

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)

Page 42: 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.

Dynamic Determination

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

Encryptor

<<dynamic>> cipherImpl

setCipherImpl()encrypt()

IDEA_Cipher

encrypt()

<<SymmetricCipher>>

Encryptor.encrypt() delegates out to a particular implementation's encrypt() method

Page 43: 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.

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

Page 44: 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.

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”?

Employee1

classificationCode = (HOURLY,SALARIED)

HourlyClassification SalariedClassification

Employee2

classificationCode

ClassificationCode

Page 45: 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.

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)

Page 46: 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.

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

Page 47: 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.

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

Page 48: 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.

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.*;

Page 49: 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.

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]

Page 50: 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.

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.

Page 51: 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.

The Infamous Java CLASSPATH

• Think of CLASSPATH as akin to PATH• On Unix, CLASSPATH entries are separated by colons

(:)• On Windoze, CLASSPATH entries are separated by

semicolons (;) • Think of the hierarchy of a subdirectory• Package declaration example:

package edu.uchicago.cs.MyClass• Example: MyClass.java, MyClass2.java and that other

class• What’s really going on?• Refer to Horstmann’s PackageTest.java sample program

on your own time—type it in!!!

Page 52: 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.

How the JVM finds classes using CLASSPATH

• CLASSPATH=/home/mark:/home/mark/myclasses:.

• You execute the command:

– java edu.uchicago.cs.YoudBetterUnderstandThis

• When the JVM executes, it looks for a class called YoudBetterUnderstandThis.class in the following directories:

/usr/local/jre/lib/edu/uchicago/cs/YoudBetterUnderstandThis.class

/usr/local/jre/lib/ext/edu/uchicago/cs/YoudBetterUnderstandThis.class

/home/mark/edu/uchicago/cs/YoudBetterUnderstandThis.class

/home/mark/myclasses/edu/uchicago/cs/YoudBetterUnderstandThis.class

./edu/uchicago/cs/YoudBetterUnderstandThis.class