meljun cortes java lecture oop

50
Object-Oriented Object-Oriented Programming Programming Java Fundamentals and Object Java Fundamentals and Object Oriented Programming Oriented Programming The Complete Java Boot Camp The Complete Java Boot Camp MELJUN CORTES MELJUN CORTES MELJUN CORTES MELJUN CORTES

Upload: meljun-cortes

Post on 13-May-2015

167 views

Category:

Technology


2 download

DESCRIPTION

MELJUN CORTES Java Lecture OOP

TRANSCRIPT

Page 1: MELJUN CORTES Java Lecture OOP

Object-Oriented Object-Oriented ProgrammingProgramming

Java Fundamentals and Object Java Fundamentals and Object Oriented ProgrammingOriented Programming

The Complete Java Boot CampThe Complete Java Boot Camp

MELJUN CORTESMELJUN CORTES

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN CORTES Java Lecture OOP

What You Should LearnWhat You Should Learn

I.I. What is OOP?What is OOP?A.A. HistoryHistory

B.B. DefinitionDefinition

C.C. GoalsGoals

II.II. What is an Object?What is an Object?A.A. DefinitionDefinition

B.B. ““Interface”Interface”

C.C. ““Class” vs. Class” vs. “Instance”“Instance”

III.III. Three Core Three Core Principles of OOPPrinciples of OOP

A.A. EncapsulationEncapsulation

B.B. InheritanceInheritance

C.C. PolymorphismPolymorphism

Page 3: MELJUN CORTES Java Lecture OOP

Why OOP? A little history…Why OOP? A little history…

The “Software Crisis” (1960’s – 1980’s)The “Software Crisis” (1960’s – 1980’s) Computers became more powerful, and so programs Computers became more powerful, and so programs

became larger and more complex. became larger and more complex. Software quality became terrible!Software quality became terrible!

Too many bugs. Schedules were not being met. Difficult to add features or make changes to software. Existing code could not be made the building blocks

for new code – easier to write from scratch! The field of “software engineering” was born!The field of “software engineering” was born!

Page 4: MELJUN CORTES Java Lecture OOP

Software EngineeringSoftware Engineering

““creating high-quality software systems in creating high-quality software systems in an efficient and predictable manner”an efficient and predictable manner”

AbstractionAbstraction was one of the prime concepts was one of the prime concepts used to simplify programming problemsused to simplify programming problems

Page 5: MELJUN CORTES Java Lecture OOP

AbstractionAbstraction

WikipediaWikipedia: “abstraction is a mechanism : “abstraction is a mechanism and practice to and practice to reduce and factor out detailsreduce and factor out details so that one can so that one can focus on a few concepts at a focus on a few concepts at a timetime””

Page 6: MELJUN CORTES Java Lecture OOP

Abstraction – evolutionsAbstraction – evolutions

Procedural ProgrammingProcedural Programming routines were grouped into “functions”routines were grouped into “functions”

one function can call another functionone function can call another function

you didn't have to understand each line, just you didn't have to understand each line, just what each function didwhat each function did

you could hide data to be accessible to only you could hide data to be accessible to only within a function (“encapsulation”)within a function (“encapsulation”)

Page 7: MELJUN CORTES Java Lecture OOP

Abstraction – evolutionsAbstraction – evolutions

Structured ProgrammingStructured Programming

further refinement of procedural further refinement of procedural programmingprogramming

formal methods of planning data-flow and formal methods of planning data-flow and functional decompositionfunctional decomposition

““goto” bannedgoto” banned

Page 8: MELJUN CORTES Java Lecture OOP

Abstraction – evolutionsAbstraction – evolutions

Object-Oriented ProgrammingObject-Oriented Programming Takes Takes encapsulationencapsulation even further by even further by

localizing data localizing data and associated operationsand associated operations into a mini-program called an “object”.into a mini-program called an “object”.

An OO program is an “ecosystem” of objects An OO program is an “ecosystem” of objects that interact with each other.that interact with each other.

Page 9: MELJUN CORTES Java Lecture OOP

What is Object Oriented What is Object Oriented Programming?Programming? ““Think of an OO system as a bunch of Think of an OO system as a bunch of

intelligent animals (the objects) inside intelligent animals (the objects) inside your machine, talking to each other by your machine, talking to each other by sending messages to one another.” – sending messages to one another.” – Allan HolubAllan Holub

Page 10: MELJUN CORTES Java Lecture OOP

What is Object Oriented What is Object Oriented Programming?Programming? OOP takes abstraction furthest by OOP takes abstraction furthest by

allowing you to group related data and allowing you to group related data and operations into different types of objects.operations into different types of objects. You no longer have to keep track of each You no longer have to keep track of each

variable or each function, just the different variable or each function, just the different types of objects.types of objects.

Page 11: MELJUN CORTES Java Lecture OOP

What is Object Oriented What is Object Oriented Programming?Programming? You create your own data types, which are You create your own data types, which are

types of objects. Each of these data types types of objects. Each of these data types are called “are called “classesclasses”.”.

Page 12: MELJUN CORTES Java Lecture OOP

What is Object Oriented What is Object Oriented Programming?Programming? Creating your own classes allows you to Creating your own classes allows you to

design a program so that it is intuitive to design a program so that it is intuitive to remember how it is organized.remember how it is organized. For example, you can create classes that For example, you can create classes that

represent real-world business entities.represent real-world business entities. You can create classes to have specific You can create classes to have specific

responsibilities, so that when you need to responsibilities, so that when you need to update a piece of code, you know exactly update a piece of code, you know exactly where to look for it.where to look for it.

Page 13: MELJUN CORTES Java Lecture OOP

Goals of OOPGoals of OOP

Comprehensibility Comprehensibility - make it easier for humans - make it easier for humans to understand the codeto understand the code

Maintainability Maintainability - make code easy to modify- make code easy to modify

Reusability Reusability - old code should be building blocks - old code should be building blocks for new codefor new code

Pluggability Pluggability - you can create interchangeable - you can create interchangeable components that can substitute for one another, components that can substitute for one another, just like machine partsjust like machine parts

Page 14: MELJUN CORTES Java Lecture OOP

What is an Object?What is an Object?

Has attributesHas attributes properties or componentsproperties or components

Has methodsHas methods behaviors or routinesbehaviors or routines

Page 15: MELJUN CORTES Java Lecture OOP

What is an Object?What is an Object?

Ex: CarEx: Car Attributes:Attributes:

steering wheelsteering wheel engineengine colorcolor radioradio airconditionerairconditioner

Methods:Methods: go forwardgo forward go backwardgo backward cool the interiorcool the interior play musicplay music

Page 16: MELJUN CORTES Java Lecture OOP

What is an Object?What is an Object?

Ex: Purchase OrderEx: Purchase Order Attributes:Attributes:

PO NumberPO Number BuyerBuyer SellerSeller List of items being List of items being

purchasedpurchased

Methods:Methods: get PO numberget PO number get buyerget buyer get sellerget seller get number of itemsget number of items get item number __get item number __

Page 17: MELJUN CORTES Java Lecture OOP

What is an Object?What is an Object?

Ex: DB ConnectionEx: DB Connection Attributes:Attributes:

URL of DBURL of DB useruser passwordpassword transaction isolation transaction isolation

levellevel is read-only? (boolean)is read-only? (boolean) is auto-commit? is auto-commit?

(boolean)(boolean)

Methods:Methods: create SQL statementcreate SQL statement return whether read-return whether read-

onlyonly set transaction set transaction

isolation levelisolation level close connectionclose connection set save pointset save point rollbackrollback

Page 18: MELJUN CORTES Java Lecture OOP

What is an Interface?What is an Interface?

An object has an “An object has an “interfaceinterface”.”. The outward appearance of an object. How The outward appearance of an object. How

other objects see the object.other objects see the object. The attributes and methods that the object The attributes and methods that the object

exposes.exposes.

Page 19: MELJUN CORTES Java Lecture OOP

What is an Interface?What is an Interface?

Normally, an object will only expose some of its Normally, an object will only expose some of its attributes and methods.attributes and methods.

Some attributes and methods are used only by Some attributes and methods are used only by the object itself. Therefore, no other object the object itself. Therefore, no other object should have access to those.should have access to those.

Some attributes and methods may be made Some attributes and methods may be made accessible only to certain other objects.accessible only to certain other objects.

Some attributes and methods may be accessible Some attributes and methods may be accessible by any other object.by any other object.

Page 20: MELJUN CORTES Java Lecture OOP

What is an Interface?What is an Interface?

Normally, only methods are exposed. Normally, only methods are exposed. Objects usually hide their data to protect Objects usually hide their data to protect them from being changed by other objects them from being changed by other objects without their control.without their control.

Constants are an exception. These don’t Constants are an exception. These don’t change anyway.change anyway.

Page 21: MELJUN CORTES Java Lecture OOP

What is a “Class” and an What is a “Class” and an “Instance”?“Instance”? My car is a ’92 Nissan Sentra. That is it’s My car is a ’92 Nissan Sentra. That is it’s

class. There are many other ’92 Nissan class. There are many other ’92 Nissan Sentras out there.Sentras out there.

But there is only one instance of my car. But there is only one instance of my car.

Page 22: MELJUN CORTES Java Lecture OOP

What is a “Class” and an What is a “Class” and an “Instance”?“Instance”? Class – the definition of an objectClass – the definition of an object Instance – the created object of a classInstance – the created object of a class

Page 23: MELJUN CORTES Java Lecture OOP

Three Core Principles of Three Core Principles of OOPOOP EncapsulationEncapsulation InheritanceInheritance PolymorphismPolymorphism

(note: different texts will have differing sets of core principles)(note: different texts will have differing sets of core principles)

Page 24: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

Encapsulation has two definitions:Encapsulation has two definitions: The grouping of data and operations into The grouping of data and operations into

objects. objects. Hiding of data and operations from other Hiding of data and operations from other

objects.objects.

Page 25: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

The first definition can be described as The first definition can be described as ““CohesionCohesion”.”.

Related data and operations should not be Related data and operations should not be separated. They should be found in a separated. They should be found in a single object.single object.

Page 26: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

Ex: CarEx: Car You shouldn’t have to ask someone with a You shouldn’t have to ask someone with a

radar gun to measure the speed of your radar gun to measure the speed of your car. Your car should have its own car. Your car should have its own speedometer to tell you that.speedometer to tell you that.

Page 27: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

Ex: Purchase Order objectEx: Purchase Order object Data for purchase orders should not be Data for purchase orders should not be

lumped in the same objects as data for lumped in the same objects as data for invoices and receipts. invoices and receipts.

The methods for retrieving data from a The methods for retrieving data from a purchase order should not be found in a purchase order should not be found in a separate class from the data.separate class from the data.

Page 28: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

Ex: DB Connection objectEx: DB Connection object The DB Connection object should not The DB Connection object should not

need to lookup the URL to the database need to lookup the URL to the database from another object every time it does an from another object every time it does an operation. operation.

Page 29: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

The other definition can be defined as The other definition can be defined as “information hiding”.“information hiding”.

An object should expose only what is An object should expose only what is necessary, and only at the appropriate necessary, and only at the appropriate level.level.

Think CIA... “need-to-know”.Think CIA... “need-to-know”.

Page 30: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

Ex: CarEx: Car To driver: only steering wheel, pedals, and stick To driver: only steering wheel, pedals, and stick

shift exposed. Driver should not access engine shift exposed. Driver should not access engine or gears or axle to drive the car.or gears or axle to drive the car.

Mechanic: access to engine, gears, etc., but not Mechanic: access to engine, gears, etc., but not internals of each part.internals of each part.

Manufacturer: access to internals of each part.Manufacturer: access to internals of each part.

Page 31: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

Ex: Purchase Order objectEx: Purchase Order object Any object can get info from the object, Any object can get info from the object,

but only certain objects should have but only certain objects should have authority to set info.authority to set info.

Only certain objects should be allowed to Only certain objects should be allowed to create the PO object.create the PO object.

Page 32: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

Ex: DB Connection objectEx: DB Connection object Only the Driver Manager object can create Only the Driver Manager object can create

a connectiona connection Users cannot set whether a connection is Users cannot set whether a connection is

read-only or not.read-only or not.

Page 33: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

Benefits:Benefits: Simpler Simpler interfacesinterfaces

Only a few methods are exposed to other Only a few methods are exposed to other objects. Since interactions between objects objects. Since interactions between objects are simple, system is easier for the are simple, system is easier for the programmer to comprehend.programmer to comprehend.

Data protected from corruptionData protected from corruption Easier to modify code or find bugsEasier to modify code or find bugs

Because of simpler interfaces.Because of simpler interfaces.

Page 34: MELJUN CORTES Java Lecture OOP

What is Encapsulation?What is Encapsulation?

Objects should only expose members to each Objects should only expose members to each other through well-defined and simple interfaces.other through well-defined and simple interfaces.

Example: A driver drives a car with only steering Example: A driver drives a car with only steering wheel, pedals, gear-shift and dashboard meters wheel, pedals, gear-shift and dashboard meters and gauges.and gauges.

Changes in one component will not affect the Changes in one component will not affect the others since the interfaces remain the same.others since the interfaces remain the same.

Page 35: MELJUN CORTES Java Lecture OOP

InheritanceInheritance

A way to create a new class by “deriving” A way to create a new class by “deriving” from another class. from another class. The new class acquires the interface of the old The new class acquires the interface of the old

class. - “Interface Inheritance”class. - “Interface Inheritance” The new class often also acquires the The new class often also acquires the

implementations of the old class. - implementations of the old class. - “Implementation Inheritance”“Implementation Inheritance”

The new class can change the The new class can change the implementations of the older class or add its implementations of the older class or add its own methods and attributes.own methods and attributes.

Page 36: MELJUN CORTES Java Lecture OOP

InheritanceInheritance

Subclasses become “sub-types” of the super Subclasses become “sub-types” of the super classes.classes.

Page 37: MELJUN CORTES Java Lecture OOP

InheritanceInheritance

You can choose to refer to a class by one of its You can choose to refer to a class by one of its super types if you only need the generic super types if you only need the generic interface.interface.

You can choose to refer to a class by its specific You can choose to refer to a class by its specific type if you only need the specialized interface.type if you only need the specialized interface.

Page 38: MELJUN CORTES Java Lecture OOP

InheritanceInheritance

Component

Button Checkbox Container TextComponent

TextArea TextFieldWindow

Dialog Frame

Example of an actual class heirarchy, part Example of an actual class heirarchy, part of the Java GUI library:of the Java GUI library:

Page 39: MELJUN CORTES Java Lecture OOP

InheritanceInheritance

Inheritance is a way to allow objects to Inheritance is a way to allow objects to share code, preventing share code, preventing code-duplicationcode-duplication.. Code-duplication is the #1 sin in OOP.Code-duplication is the #1 sin in OOP.

Page 40: MELJUN CORTES Java Lecture OOP

InheritanceInheritance

Implementation inheritance is dangerous!Implementation inheritance is dangerous! The Fragile Base Class ProblemThe Fragile Base Class Problem

A subclass must inherit all inheritable members of the superclass.

No option to “disinherit” a member. If the subclass inherits members that it doesn’t

need, those members might be called by other objects in a way that the creator of the subclass did not intend (remember, you’re working in a team) causing undesirable behavior.

Page 41: MELJUN CORTES Java Lecture OOP

InheritanceInheritance

Implementation inheritance is dangerous!Implementation inheritance is dangerous! The Fragile Base Class ProblemThe Fragile Base Class Problem

If someone modifies the superclass, the subclass will inherit the change!

Again, this might cause undesirable behavior!

Page 42: MELJUN CORTES Java Lecture OOP

InheritanceInheritance

Implementation inheritance is dangerous!Implementation inheritance is dangerous! Other issues:Other issues:

Long hierarchies become complex and difficult to manage.

Long hierarchies lead to classes with complex interfaces.

Page 43: MELJUN CORTES Java Lecture OOP

InheritanceInheritance

Implementation inheritance is dangerous!Implementation inheritance is dangerous! Prefer interface inheritance to implementation Prefer interface inheritance to implementation

inheritance. At least you don’t inherit inheritance. At least you don’t inherit behavior, just the interface.behavior, just the interface.

Never extend a class simply to save yourself Never extend a class simply to save yourself some typing! There has to be a strong logical some typing! There has to be a strong logical “is-a” relationship between superclass and “is-a” relationship between superclass and subclass.subclass.

Page 44: MELJUN CORTES Java Lecture OOP

PolymorphismPolymorphism

When a single datatype exhibits different When a single datatype exhibits different behaviors during execution.behaviors during execution.

Greek: Poly means “many”, morph means Greek: Poly means “many”, morph means “form”. Polymorphism means “existing in “form”. Polymorphism means “existing in many forms”.many forms”.

Page 45: MELJUN CORTES Java Lecture OOP

PolymorphismPolymorphism

It is the other side of the same coin as It is the other side of the same coin as Inheritance.Inheritance.

Polymorphism is Polymorphism is the reasonthe reason why we want why we want to have inheritance.to have inheritance.

Page 46: MELJUN CORTES Java Lecture OOP

PolymorphismPolymorphism

Polymorphism allows for “pluggability” or Polymorphism allows for “pluggability” or “substitutability”.“substitutability”. Types that implement the same interface can Types that implement the same interface can

substitute for one another. substitute for one another. Client code just sees one class, but the actual Client code just sees one class, but the actual

“concrete” type can be different in different “concrete” type can be different in different cases.cases.

Page 47: MELJUN CORTES Java Lecture OOP

PolymorphismPolymorphism

Method Overriding Method Overriding when a subclass re-implements one or more when a subclass re-implements one or more

methods from the superclassmethods from the superclass changes the behavior of the methodchanges the behavior of the method

Page 48: MELJUN CORTES Java Lecture OOP

PolymorphismPolymorphism

You can pass a subclass to a method You can pass a subclass to a method wherever a particular class is required.wherever a particular class is required.

void add(Component c);void add(Component c); you can pass instance of Button, TextArea,

Dialog, etc, since they all inherit the interface of Component

Page 49: MELJUN CORTES Java Lecture OOP

PolymorphismPolymorphism

Since each subclass implements the methods of Since each subclass implements the methods of Component differently, each subtype gets drawn Component differently, each subtype gets drawn differently, receives input differently, listens for differently, receives input differently, listens for different events, etc.different events, etc.

void add(Component c);void add(Component c); you can pass instance of Button, TextArea,

Dialog, etc, since they all inherit the interface of Component

Page 50: MELJUN CORTES Java Lecture OOP

The EndThe End

Java Fundamentals and Object-Oriented Java Fundamentals and Object-Oriented ProgrammingProgramming

The Complete Java Boot CampThe Complete Java Boot Camp