Introduction and Review of Java: Part 2 Fundamental Concepts (Principles) of Object Oriented Programming Java s implementation of Object Oriented Programming 1of 59
WHAT IS OBJECT ORIENTED PROGRAMMING? OOP was invented to mitigate the increasing complexity of software trying to make software simpler and more manageable. The Object Oriented approach is to view software the same way we view the world easier for us to understand. OOP is a way of thinking about how to create computer programs to solve problems Everything is an object, and objects communicate between each other and collaborate to implement tasks. Consider how we might go about handling a realworld situation and then ask how we could design software to do the same. 2of 59
ILLUSTRATION OF OO CONCEPTS SENDING FLOWERS TO A FRIEND Consider the problem of sending flowers to a friend who lives in a different city. Chris is sending flowers to Robin. Chris can t deliver them directly. So Chris uses the services of the local Florist. Chris tells the Florist (named Fred) Robin s address, how much to spend, and the type of flowers to send. Fred contacts a florist in Robin s city, who arranges the flowers, then contacts a driver, who delivers the flowers. 3of 59
COMMUNITY OF AGENTS (OBJECTS) HELPING DELIVER FLOWERS Chris Fred:Florist :Wholesaler :Grower :Gardener Robin sflorist :FlowerArranger Robin :DeliveryPerson UML INSTANCE DIAGRAM 4of 59
NOTES ON EXAMPLE (1) Each agent has additional things (responsibilities) that it can do requests that it can fill out Set of responsibilities is called the object s protocol. Each agent has data that belongs to itself data that it must remember to manage its state Example: Fred must remember the transaction with Chris and with Robin s florist. Fred operates on his data, exclusively data encapsulation. 5of 59
NOTES ON EXAMPLE (2) A requesting agent does not care about how the receiving agent implements a request Information hidingand abstraction Different receiving agents may implement a request in different ways Polymorphism. Each requesting agent must trust the receiving agent to fulfill the request appropriately Reuse of existing components. 6of 59
NOTES ON EXAMPLE (3) Agents of the same type are similar, and they may be classified as a class Other Florists, like Jane, Samantha, and Fernando Other Gardeners, etc. Class for Florists, Gardeners, DeliveryPerson, etc. Each class can be organized into a hierarchy Fred is a Florist, Florist is Shopkeeper, Shopkeeper is a Human, Human is a Mammal, Mammal is an Animal, Animal is a Material Object. Classes inherit properties of upper layer classes Inheritance Hierarchy. 7of 59
CATEGORIES SURROUNDING FRED MaterialObject Animal Mammal Human Shopkeeper Florist NON STANDARD DIAGRAM UML CLASS DIAGRAM (SHOWING INHERITANCE) 8of 59
A CLASS IHERITANCE HIERARCHY UML CLASS DIAGRAM MaterialObject Animal Plant Mammal Flower Dog Human Platypus Carnation Shopkeeper Artist Dentist Florist Potter 9of 59
FUNDAMENTAL CHARACERISTICS (PRINCIPLES) OF OBJECT ORIENTED (OO) PROGRAMMING 1. Everything is an object Each object has a set of responsibilities (behavior), a set of things it can do Each object has it own data, which it manages, exclusively. 2. Objects send messages (requests) to one another. A message may contain additional information needed to carry out the request. Messages are usually implemented as methods, a way in which a request is implemented Additional information is encoded in the argument list of the method. 10 of 59
FUNDAMENTAL CHARACERISTICS (PRINCIPLES) OF OBJECT ORIENTED (OO) PROGRAMMING 3. Classes may be organized in an inheritance hierarchy, where higher layers contain more general information and lower layers contain more specific information about the class. Lower layer classes in the hierarchy inherit properties of higher layer classes in the hierarchy. 4. Reuse and reusable components 5. Information hiding and abstraction 6. Polymorphism 11 of 59
JAVA OO PROGRAMMING Object An object has state and behavior. Class A class is a blueprint from which objects are created. Inheritance Inheritance provides a powerful and natural mechanism for organizing and structuring your software. Interface An interface is a contract between a class and the outside world. Package A package is a namespace for organizing classes and interfaces in a logical manner. 12 of 59
WHAT IS AN OBJECT? Object Oriented Technology views software in the same way we view real world objects: Real world objects share two characteristics They all have state and behavior. Examples of real world objects Dogs State: name, color, breed, hungry Behavior: barking, fetching, wagging tail. Bicycles State: current gear, current pedal cadence, current speed Behavior: changing gear, changing pedal cadence, applying brakes. 13 of 59
WHAT IS AN OBJECT? Desktop radio States: on, off, current volume, current station Behavior: turn on, turn off, increase volume, decrease volume, seek, scan, and tune. Some objects will also contain other objects Example: Automobiles States: color, make, model, Transmission, weight, etc. Behavior: start, brake, increase speed, etc. Transmission States: park, reverse, drive, etc. Behavior: change gears, increase speed, etc. 14 of 59
A SOFTWARE OBJECT IN JAVA Software objects consist of state and related behavior Stores its state in fields (variables) Exposes its behavior through methods. Methods Operate on an object s internal state, and Serve as the primary mechanism for object to object communication. Data Encapsulation Hiding internal state and requiring all interaction to be performed through an object s methods is known as data encapsulation a fundamental principle of object oriented programming. 15 of 59
A SOFTWARE OBJECT REPRESENTATION The object remains in control of how the outside world is allowed to use it. OF A BICYCLE For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6. 16 of 59
BENEFITS OF OBJECT ORIENTATION Modularity The source code for an object can be written and maintained independently of the source code for other objects. Once written, the source code for an object can be easily passed around inside the system. Information hiding By interacting only with an object s methods, the details of its internal implementation remain hidden from the outside world Reduces complexity. The details of its internal implementation can be changed without affecting other objects that use it. 17 of 59
BENEFITS OF OBJECT ORIENTATION Data Encapsulation Only the object's own methods can directly inspect or manipulate its fields. Decreases complexity because we don t have to worry about any code changing the internal state of an object, except for the object s own methods. Not enforced in Java, but considered good OO programming practice. Code re use A fundamental principle of software engineering is basing software development of re usable technology. Reusing already tested/debugged objects leads to higher quality software. 18 of 59
BENEFITS OF OBJECT ORIENTATION Plug ability and debugging ease Because objects are self contained and independent, objects of the same type and same signature can be interchanged in an application very simply. If you discover an object that is more efficient than yours, you can replace your object with the more efficient object, provided the signature is the same. If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. EX: If a bolt breaks, you replace it, not the entire machine. 19 of 59
WHAT IS A CLASS? In the real world, you ll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object oriented terms, we say that your bicycle is an instance of the class of objects known as Bicycle. A class is the blueprint from which individual objects are created. 20 of 59
JAVA CODE FOR Bicycle CLASS class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changecadence(int newvalue) { cadence = newvalue; void changegear(int newvalue) { gear = newvalue; void speedup(int increment) { speed = speed + increment; void applybrakes(int decrement) { speed = speed - decrement; void printstates() { System.out.println("cad:"+cadence+" spd:"+speed+" gear:"+gear); 21 of 59
Bicycle CLASS DECLARATION class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changecadence(int newvalue) { cadence = newvalue; void changegear(int newvalue) { gear = newvalue; void speedup(int increment) { speed = speed + increment; void applybrakes(int decrement) { speed = speed - decrement; void printstates() { System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear); 22 of 59
Bicycle CLASS FIELDS: STATE class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changecadence(int newvalue) { cadence = newvalue; void changegear(int newvalue) { gear = newvalue; void speedup(int increment) { speed = speed + increment; void applybrakes(int decrement) { speed = speed - decrement; void printstates() { System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear); 23 of 59
Bicycle CLASS METHODS: BEHAVIOR class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changecadence(int newvalue) { cadence = newvalue; void changegear(int newvalue) { gear = newvalue; void speedup(int increment) { speed = speed + increment; void applybrakes(int decrement) { speed = speed - decrement; void printstates() { System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear); 24 of 59
Bicycle DEMO CLASS APPLICATION THAT INTERACTS WITH THE Bicycle CLASS class BicycleDemo { public static void main(string[] args) { // Create two different Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on those objects bike1.changecadence(50); bike1.speedup(10); bike2.changecadence(50); 25 of 59
UML REPRESENTATION OF A CLASS Name of class Bicycle gear speed changegear speedup List of Fields List of Methods 26 of 59
UML CLASSES AND ASSOCIATION BicycleDemo has a reference to Bicycle (indicated by the arrow). Bicycle gear speed changegear speedup BicycleDemo main() Line of Association. Bicycle does NOT have a reference to BicycleDemo (indicated by the lack of an arrow). 27 of 59
UML SEQUENCE DIAGRAM EXAMPLE: OBJECTIVE: TO SHOW HOW BicyleDemo CREATES AND SENDS MESSAGES TO Bicycle OBJECTS. User BicycleDemo Bicycle: bike1 Bicycle: bike2 java BicycleDemo create create main() changecadence(50) speedup(10) changecadence(50) 28 of 59
UML NOTES Class diagram Shows a static view of the program (system); i.e., it describes what classes are in the system and how they are related (association) Abstracted view of system Need to identify the objective for showing a class diagram Not all classes or components of classes need to be shown Show only the items which are needed to get your point (objective) across. Sequence diagram 29 of 59
UML NOTES: CLASS DIAGRAM Shows a static view of the program (system) It describes what classes are in the system and how they are related (association). Abstracted view of system Need to identify the objective for showing a class diagram Not all classes or components of classes need to be shown Show only the items which are needed to get your point (objective) across. 30 of 59
UML NOTES: SEQUENCE DIAGRAM Shows a dynamic view of the program (system) It describes the interaction between items in the system Items can be users, classes, objects, etc. Abstracted view of system Need to identify the objective for showing a sequence diagram Not all items in the system need to be shown Show only the items which are needed to get your point (objective) across. 31 of 59
WHAT IS INHERITANCE? Consider the blueprints (classes) of different types of bicycles. Examples: Tandem, Road, and Moumtain bikes The objects of these different types have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different Tandem bicycles have two seats and two sets of handlebars Road bikes have drop handlebars Mountain bikes have an additional chain ring: for lower gear ratio. It would be redundant to duplicate the code to describe the common fields and common behavior of these different types of bicycles. 32 of 59
WHAT IS INHERITANCE? Object oriented programming allows classes to inherit commonly used state and behavior from other classes. For example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. 33 of 59
UML REPRESENTATION OF INHERITANCE Superclass Bicycle gear changegear Closed, non filled, solid line triangle points to the superclass MountianBike chainring changechainring RoadBike handlebarpos changehandlebarpos TandemBike seat Subclass Subclass Subclass 34 of 59
INHERITANCE SYNTAX At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle { // New fields and new methods that make // a mountain bike different than a // Bicycle would go here. This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make MountainBike unique. 35 of 59
INHERITANCE EXAMPLE class MountainBike extends Bicycle { int seatheight; public void setheight(int newvalue) { seatheight = newvalue; public int getheight() { return seatheight; MountainBike inherits all the fields and methods of Bicycle and adds the field seatheight and methods to get and set it. 36 of 59
INHERITANCE RULES Java programming language specific rules Each class is allowed to have a maximum of one direct superclass. To minimize complexity Each superclass has the potential for an unlimited number of subclasses. Good Object Oriented practice rules Ensure each subclass obeys the 1. ISA rule 2. Distinctiveness rule 3. Rule that all inherited features make sense in each subclass. 37 of 59
INHERITANCE RULES: ISA RULE Ensure each subclass obeys the ISA rule A chequing account is an account. A village is a municipality. A mountain bike is a bike. Should Province be a subclass of Country? No, a Province is not a Country. Modeling a Province as a Country violates the ISA rule. Modeling a Province as Country would artificially introduce complexity into the source code, making the source code more difficult to understand, maintain, and use. 38 of 59
INHERITANCE RULES: DISTINCTIVENESS RULE A subclass must retain its distinctiveness throughout its life. Consider a bike with training wheels, for teaching kids to ride. You might consider creating a class called TrainingBicycle, and making this a subclass of Bicycle. However, a training wheel bicycle will not be a training bike once the training wheels are removed. Therefore, TrainingBicycle is not a subclass of Bicycle. Modeling a TrainingBicycle as a Bicycle would artificially introduce complexity into the source code, making the source code more difficult to understand, maintain, and use. Actually, TrainingBicycle should not even be a class. It s better to have a field that indicates if a Bicycle has training wheels. 39 of 59
INHERITANCE RULES: MSFMS Make Sure that each Feature of a superclass Makes Sense in each subclass. Each subclass inherits the features of a superclass. Modeling a class as a subclass of some superclass with one or more features that do not make sense in the subclass would artificially introduce complexity into the source code, making the source code more difficult to understand, maintain, and use. 40 of 59
ADVANTAGES OF INHERITANCE Only one copy of the common features of a set of subclasses is coded: they are coded only in the superclass No duplication of code Avoids errors of copying the features to each of the subclasses More flexible for change, for examples: Replacing a more efficient method in the superclass means each of the subclasses will also have the benefit of the more efficient method, since it is inherited Adding/removing fields to/from the superclass affects all classes underneath the superclass 41 of 59
WHAT IS AN INTERFACE? Objects define their interaction with the outside world through the methods that they expose. Methods form the object s interface with the outside world. For example, The buttons on the front of your television set are the interface between you and the electrical, electronic, and digital circuits on the other side of its plastic casing. You press the power button to turn the television on and off. 42 of 59
MOTIVATION FOR HAVING AN INTERFACE 1. The main reason for having an interface is CONVENIENCE. Suppose you have written several re usable classes that offer a main point of functionality, which is implemented by a set of primary methods, but that the classes had other methods which are either supporting methods or for another purpose You want to give other developers easier access to the primary methods of the main point of functionality. It would be good if: Developers did not have to search through your set of classes and determine what are the desired primary methods There was a mechanism to publish (make known) the primary methods in a single container (Interface) This would be more convenient. 43 of 59
MOTIVATION FOR HAVING AN INTERFACE 2. Easier to replace objects in the system The required methods an object needs to provide to a system is formalized and published in the interface The interface or set of interfaces could be the only connection the object has with the other objects in the system Therefore, to replace an object with a new one, the new object need only implement the required interface. 44 of 59
JAVA INTERFACE Java provides such a mechanism, called an interface. An interface is a formal specification of a set of related methods that a class (or a group of classes) provides and implements. In Java, an interface is a group of related methods with empty bodies. A class (or group of classes) provides the implementation of the methods specified in the interface. 45 of 59
INTERFACE: BICYCLE EXAMPLE To specify (or advertise) the methods that the Bicycle hierarchy provides to effect speed (i.e., a main point of functionality), consider creating an interface called BicycleSpeed. interface BicycleSpeed { void setcadence(int newvalue); void setgear(int newvalue); void speedup(int increment); Now, a developer need not search the Bicycle hierarchy for the methods that effect speed: that information is contained in the BicycleSpeed interface. Note: there is no body for each method in the interface, as required. Methods with no bodies are called abstract methods. 46 of 59
INTERFACE: BICYCLE EXAMPLE To implement this interface, use the implements keyword in the class declaration. class Bicycle implements BicycleSpeed { void setcadence(int newvalue){ //code for changing the cadence. void setgear(int newvalue){ // code for changing the gear. //Other methods interface BicycleSpeed { void setcadence(int newvalue); void setgear(int newvalue); 47 of 59
UML REPRESENTATION OF INTERFACE Dashed line connects the class with the interface. Interface «interface» BicycleSpeed setcadence setgear This class hierarchy implements the interface BicycleSpeed. Bicycle setcadence setgear Closed, non filled, dashed line triangle points to the interface MountainBike RoadBike TandemBike chainring changechainring handlebarpos changehandlebarpos seat 48 of 59
SIMPLE APPLICATION PURPOSE: TO CHANGE SPEED OF A MOUNTAIN BIKE BicycleDemo «interface» BicycleSpeed setcadence setgear User of the Bicycle hierarchy for the sole purpose of changing speed of a mountain bike. TandemBike Bicycle setcadence setgear MountainBike Assume Bicycle Hierarch is very Complex 49 of 59
Bicycle CLASS IN FILE Bicycle.java public class Bicycle implements BicycleSpeed { // the Bicycle class has three fields public int cadence; public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int startcadence, int startspeed, int startgear) { gear = startgear; cadence = startcadence; speed = startspeed; 50 of 59
Bicycle CLASS (CONTINUED) // the Bicycle class has four methods public void setcadence(int newvalue) { cadence = newvalue; public void setgear(int newvalue) { gear = newvalue; public void applybrake(int decrement) { speed -= decrement; public void speedup(int increment) { speed += increment; 51 of 59
MountainBike CLASS IN FILE BountainBike.java public class MountainBike extends Bicycle { // the MountainBike subclass adds one field public int seatheight; // the MountainBike subclass has one constructor public MountainBike(int startheight, int startcadence, int startspeed, int startgear) { super(startcadence, startspeed, startgear); seatheight = startheight; // the MountainBike subclass adds one method public void setheight(int newvalue) { seatheight = newvalue; 52 of 59
BicycleSpeed INTERFACE IN FILE BicycleSpeed.java interface BicycleSpeed { void setcadence(int newvalue); void setgear(int newvalue); void speedup(int increment); 53 of 59
BicycleDemo CLASS IN FILE BicycleDemo.java public class BicycleDemo{ public static void main(string[] args) { MountainBike mymountainbike = new MountainBike(1, 2, 3, 4); BicycleSpeed speedofmymountainbike; speedofmymountainbike = mymountainbike; BicycleDemo «interface» BicycleSpeed setcadence setgear speedofmymountainbike.setcadence(5); Bicycle speedofmymountainbike.setgear(6); MountainBike System.out.printf("gear is %d%n", mymountainbike.gear); System.out.printf("cadence is %d%n", mymountainbike.cadence); 54 of 59
JAVA INTERFACE RULES Each class is allowed to implement any number of interfaces. Each method specified in an interface cannot have any implementation. Each method in an interface must have an empty body. Each method specified in an interface must be implemented by some class in the source code. If a class claims to implement an interface, all methods defined by that interface must appear in the class s source code. Otherwise the class will not compile successfully. 55 of 59
WHAT IS A PACKAGE? A package is a container in which related classes and interfaces are grouped together. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. For large programs which are composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages. 56 of 59
JAVA S PACKAGES: API The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the Application Programming Interface (API). The packages within the API represent the tasks most commonly associated with general purpose programming. 57 of 59
EXAMPLES OF JAVA PACKAGES java.lang The String, Integer, Double and other related classes are contained within the java.lang package. For example, the Integer class contains state and behavior for common integer tasks, such as Converting a string to an Integer object. java.io a File object allows a programmer to easily create, delete, inspect, or modify a file on the file system. The File and other related classes are contained within the java.io package. 58 of 59
EXAMPLES OF JAVA PACKAGES java.net a Socket object allows for the creation and use of network sockets. The Socket and other related classes are contained within the jave.net package. java.awt various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. The GUI related classes are contained within the java.awt package. There are many other packages and literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work. 59 of 59