anatomy of an object every object has 2 parts: data function data (fields) can be...
Post on 20-Dec-2015
217 views
TRANSCRIPT
Anatomy of an object• Every object has 2 parts:
• Data• Function
• Data (Fields)• Can be "primitive" data types:
• int, long, double, byte• Or other objects:
• String, Date, Name, Person, etc…• Function (Methods)
• A method is a discreet piece of functionality that an object can perform
• Like functions/procedures in other languages it can take parameters and return a value/object.
Anatomy of an object (continued)
Person
String firstName
String lastName
Date dateOfBirth
String getInitials()
int getAge( Date )
The class named Personhas 3 fields:firstName (type = String)lastName (type = String)dateOfBirth (type = Date)
and 2 methods:getInitials (no parmaters, returns a StringgetAge (1 parameter, returns an int)
A Class
Classes vs Instances• Class - an object that defines all data and
behavior for a particular type of object. Classes can be thought of as templates or factories for objects.
• Instance - an object that represents a “for real” manifestation of a class. While a class defines the data items and functions, an instance actually holds the values and “runs” the functions. There is also an allocation of memory for each instance.
Classes vs Instances (continued)
Person
String firstName
String lastName
Date dateOfBirth
String getInitials()
int getAge( Date )
Person Class Person InstancesfirstName = "Joseph"
lastName = "Smith"
dateOfBirth = 1/1/1960
firstName = "Betty"
lastName = "Boop"
dateOfBirth = 4/1/1932
getInitials() -> "JS"getAge(12/7/2003) -> 43
getInitials() -> "BB"getAge(12/7/2003) -> 71
Think of a class as a “vending machine”. Each time you “pull the lever”, an instance comes
out.
Classes vs Instances (continued)• An Instance is created from a Class
… new Person()… or, better yet
… new Person( "Joseph", "Smith", 1/1/1960 )
• The new keyword invokes a special method called a constructor method which creates an instance from a class.
Classes vs Instances (continued)Person p1, p2;
p1 = new Person("Sammy", "Sosa", 4/13/1972 );
p2 = new Person("Mickey", "Mouse", 11/2/1928);
p1.getInitials(); /* returns "SS" */
p1.getAge( 12/7/2003 ); /* returns 31 */
p2.getInitials(); /* returns "MM" */
p2.getAge( 12/7/2003 ); /* returns 75 */
3 Principles of Object Orientation (OO)
• Encapsulation• Information hiding
• Inheritance• Polymorphism
Encapsulation• The bundling of data and function together into 1
logical unit• Data and the functions that are associated with it
are closely bound together• No more "global data"
• Allows for modularity• Promotes reuse when done properly
Encapsulation (continued)
Person
String firstName
String lastName
Date dateOfBirth
String addressLine
String city
String state
String zipCode
String getInitials()
int getAge( Date )
boolean isForeign()
double salesTax()
Person
String firstName
String lastName
Date dateOfBirth
String getInitials()
int getAge( Date )
Address
String addressLine
String city
String state
String zipCode
boolean isForeign()
double salesTax()
Better…Good…
Encapsulation (continued)
Person
String firstName
String lastName
Date dateOfBirth
Address currentAddress
Address previousAddress
String getInitials()
int getAge( Date )
Address
String addressLine
String city
String state
String zipCode
boolean isForeign()
double salesTax()
Reuse in action…
Organization
String orgName
Address currentAddress
Information Hiding• Goes hand-in-hand with encapsulation• The internal workings of an object are private to that object
• this includes all data that that object holds• the only way to access any object is through its public
interface• Public – anyone can see/use it• Private – no one (only the owning class itself) can see/use
it.
public interface - the public methods of a class
Why? If everyone knew about your internal workings, any change made would make everything else break!
Information hiding (continued)Salesman
String firstName
String lastName
int itemsSold
String getInitials()
int getAge( Date )
For this Salesman class, the only thingsI can do are: getInitials() getAge()
What if I want to see the number ofItems sold?
Information hiding (continued)Salesman
String firstName
String lastName
int itemsSold
String getInitials()
int getAge( Date )
I can make my field itemsSold public
Salesman
String firstName
String lastName
int itemsSold
String getInitials()
int getAge( Date )
int getItemsSold()
I can add a new public method getItemsSold()
OR
Information hiding (continued)Salesman
String firstName
String lastName
int itemsSold
String getInitials()
int getAge( Date )
This approach reveals the internal representation of my data.
Salesman
String firstName
String lastName
int itemsSold
String getInitials()
int getAge( Date )
int getItemsSold()
This approach says that when you want itemsSold, you will get backan integer. You have no idea howit is stored or derived.
OR
Information hiding (continued)• Company policy changes and the “items sold” by
a salesperson is the average sales per-person of that salesperson group
• Everyone who directly accessed the itemsSold field will now be incorrect
• The getItemsSold() method should be updated to use this group average instead• Everyone who used the method will still be correct.
Inheritance• What is inheritance?
• The "passing on" of data and function from a parent class (superclass), to its children (subclasses)
• A child class automatically gets all of the data elements and functions from its parent
• Another form of reuse• Why inherit?
• You inherit from a superclass if you want to build a class that is very similar to the superclass but some differences are needed.
• Create a subclass if you want to extend existing functionality or add new functionality
Inheritance examplePerson
String firstName
String lastName
Date dateOfBirth
String getInitials()
int getAge( Date )
Student
String classYear
String getClassLevel()
Professor
String department
String getDepartment()
Student and Professorboth inherit from Person.
Inheritance example
PersonString firstName
String lastName
Date dateOfBirth
String getInitials()
int getAge( Date )
StudentString classYear
String getClassLevel()
ProfessorString department
String getDeptName()
Student (instance)firstName = "Sam"
lastName = "Smith"
dateOfBirth = 6/30/1986
classYear = "2006"
getInitials() -> "SS"
getAge( today ) -> 17
getClassLevel() -> "Sophomore"
Professor (instance)firstName = "Talka"
lastName = "Lotta"
dateOfBirth = 1/1/1909
dept = "0078"
getInitials() -> "TL"
getAge( today ) -> 86
getDeptName() -> "Chemistry"
Both Student and Professor inherit all of thefields and methods from their superclassPerson.Both extend Student by adding more functionality.
Adding functionality…
Inheritance example
PersonString firstName
String lastName
Date dateOfBirth
String getInitials()
int getAge( Date )
String printName()
StudentString classYear
String getClassLevel()
ProfessorString department
String getDeptName()
String printName()
/* add Prof. in front… */
Student (instance)firstName = "Sam"
lastName = "Smith"
dateOfBirth = 6/30/1986
classYear = "2006"
getInitials() -> "SS"
getAge( today ) -> 17
getClassLevel() -> "Sophomore“
printName() “Sam Smith”
Professor (instance)firstName = "Talka"
lastName = "Lotta"
dateOfBirth = 1/1/1909
dept = "0078"
getInitials() -> "TL"
getAge( today ) -> 86
getDeptName() -> "Chemistry“
printName() “Prof. Talka Lotta”
aStudent.printName() -> "Sam Smith"
aProf.printName() -> "Prof. Talka Lotta"
Overriding functionality…
Polymorphism• What is Polymorphism?
• A number of classes may all have the same method name foo(); but that method does different things depending on the class on which it is called
• This allows us to treat a group of classes similarly yet each can express its own "individuality"
Polymorphism example 2Loan
applyPayment( amount )
calculatePaymentSchedule()
getPayoffAmount()
SimpleLoan
applyPayment( amount )
calculatePaymentSchedule()
getPayoffAmount()
Mortgage
applyPayment( amount )
calculatePaymentSchedule()
getPayoffAmount()
LoanManager
applyPayments()
printCoupons()
Polymorphism example 2• LoanManager code…/* get all payments that came in today and apply to the loans */
List allPayments = getAllPayments();
/* for each payment P, find the loan for it */
…for each payment…P
Loan aLoan = findLoanForPayment( P );
/* apply the $ to the loan */
aLoan.applyPayment( P ); /* what kind of loan is this? We don't know! */
/* print out coupon booklet */
PaymentSchedule paySchedule := aLoan.calculatePaymentSchedule();
paySchedule.print(); /* another polymorphic method… */
Polymorphism example 2Loan
applyPayment( amount )
calculatePaymentSchedule()
getPayoffAmount()
SimpleLoan
applyPayment( amount )
calculatePaymentSchedule()
getPayoffAmount()
Mortgage
applyPayment( amount )
calculatePaymentSchedule()
getPayoffAmount()
MultiDisbursementLoan
applyPayment( amount )
calculatePaymentSchedule()
getPayoffAmount()
LoanManager continues to work as is when a new loan type is added.
Design Patterns• What is a design pattern?
• a.k.a. – "design approach"• A specific design approach that solves a particular
problem. • It is used so frequently that is becomes
"standardized".• It has a name
• Why do we need them?• We don't "need" them, but they can make life
easier
Design Patterns• Why use design patterns?
• A design pattern is well-understood so there is a less likely chance of the design "failing"
• Patterns have been "tested" in the real world across various application types
• Simplifies maintenance because if all developers are familiar with patterns
• Shorter learning curve
Design Patterns (examples)Factory pattern:
A Factory is a class that allows us to create instances of other classes depending on the information it is given. The factory is smart enough to figure out what instance to create
Design Patterns (examples)
Loan
SimpleLoan Mortgage
LoanFactorycreateLoan( loan info )
LoanFactory
Loaninformation
createLoan()
LoanFactory
Loaninformation
createLoan()
SimpleLoan
Mortgage
Frameworks• What is a framework
• A set of reusable designs and objects used to build applications
• Defines how objects work together to get something done
• Defines the superclasses or public interface for the object that you develop
• Your objects work within the framework
• A framework is a "semi-complete" application
Frameworks• A framework usually supports a very specific
domain• GUI (large)• Collections (small)
• Usual characteristics of a good framework• Relatively easy to understand and use• Provides a solution to a common problem• Can be used over and over again
Frameworks• To use a framework, you work with the base
classes that come with the framework• Create subclasses from base classes• Your classes implement a public interface as
defined by the framework
FrameworksPros• A lot of work is done for you
already• Shorter development time• Developers can
concentrate on business, not technology
• Shielded from technology changes
• Framework will handle changes as the vendor upgrades it
• Greater consistency across applications if they all use the same framework(s)
Cons• Tight coupling between
application and framework• "vendor lock-in"
• Extra learning curve• Framework may not
provide everything you need• Extend the FW yourself
Frameworks• STRUTS
• http://jakarta.apache.org/struts/• Web Application framework
• Provides all the “techie” stuff needed for a web application• You configure it to work the way you want it to
• Navigation• Form validation
• Easily extensible• Add your own classes if Struts doesn’t have what you need
• Lots of contributors• Constant improvement
• Supported by major IDEs• UPortal is a framework AND application!
Components• What is a component?
• An object or group of objects with a well defined public interface that provides a discreet set of functionality
• Black box• Utility object
• Different from a framework• Your objects are not tightly coupled with a component
• Do not subclass from a component
• Components are interchangeable• New component must have same API as old component
Components
LDAPAuthenticationMgr
authenticate()
Some object Authenticate( id, password)
LDAPDB
DBAuthenticationMgrauthenticate()
Authenticate( id, password)