Introduction and Review of Java: Part 2

Similar documents
Java OOP (SE Tutorials: Learning the Java Language Trail : Object-Oriented Programming Concepts Lesson )

Fundamental Concepts (Principles) of Object Oriented Programming These slides are based on:

Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem

Universiti Malaysia Perlis

Computer Science 210: Data Structures

Inheritance, part 2: Subclassing. COMP 401, Spring 2015 Lecture 8 2/3/2015

Java Programming Tutorial 1

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

Inheritance. The Java Platform Class Hierarchy

Object Oriented Software Design

Data Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

UCLA PIC 20A Java Programming

Tony Valderrama, SIPB IAP 2009

Lesson: Classes and Objects

Object oriented programming Concepts

What are the characteristics of Object Oriented programming language?

NATIONAL DIPLOMA IN COMPUTER TECHNOLOGY

Chapter No. 2 Class modeling CO:-Sketch Class,object models using fundamental relationships Contents 2.1 Object and Class Concepts (12M) Objects,

CS260 Intro to Java & Android 03.Java Language Basics

Object-oriented perspective

Chapter 2: Java OOP I

Inheritance and Polymorphism

Object-oriented. Service Innovation

CSE 21 Intro to Computing II. Inheritance

IT2301 JAVA PROGRAMMING

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 2: Review of Object Orientation

Object- Oriented Design with UML and Java Part I: Fundamentals

Object-Oriented Programming Paradigm

Lecture 2: Java & Javadoc

The class definition is not a program by itself. It can be used by other programs in order to create objects and use them.

PROGRAMMING LANGUAGE 2

Software Architecture (Lesson 2) Object-Oriented Paradigm (1)

Exercise: Singleton 1

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

What is the output of the following code segment:

JAVA: A Primer. By: Amrita Rajagopal

Object-Oriented Software Engineering. Chapter 2: Review of Object Orientation

Design Patterns. Design Patterns 1. Outline. Design Patterns. Bicycles Simulator 10/26/2011. Commonly recurring patterns of OO design

CITS2210. Object-Oriented Programming. Topic 1. Introduction and Fundamentals: Thinking Object-Oriented

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012

Inheritance and Interfaces

Defining Classes and Methods

Object Oriented Programming

Classes, subclasses, subtyping

Subclasses, Superclasses, and Inheritance

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Sri Vidya College of Engineering & Technology

Object-Oriented Modeling Using UML. CS151 Chris Pollett Aug. 29, 2005.

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

Structured Programming

1. Write two major differences between Object-oriented programming and procedural programming?

CHAPTER 5 GENERAL OOP CONCEPTS

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Lecture 2 and 3: Fundamental Object-Oriented Concepts Kenneth M. Anderson


OBJECT ORİENTATİON ENCAPSULATİON

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

CS260 Intro to Java & Android 02.Java Technology

UML - Class Diagrams

Basics of Object Oriented Programming. Visit for more.

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Lecture 5: Methods CS2301

CS111: PROGRAMMING LANGUAGE II

Learning the Java Language. 2.1 Object-Oriented Programming

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

CS313D: ADVANCED PROGRAMMING LANGUAGE

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Chapter 6 Introduction to Defining Classes

Software Development. Modular Design and Algorithm Analysis

Object Oriented Programming (Java and Visual Basic)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

C++ Programming: Introduction to C++ and OOP (Object Oriented Programming)

Example: Fibonacci Numbers

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CMSC 132: Object-Oriented Programming II

Welcome to Design Patterns! For syllabus, course specifics, assignments, etc., please see Canvas

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

C++ Important Questions with Answers

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance (Part 2) Notes Chapter 6

Introduction to Object- Oriented Programming

Another IS-A Relationship

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

OVERRIDING. 7/11/2015 Budditha Hettige 82

More Relationships Between Classes

Introduction to Design Patterns

Inheritance CSC 123 Fall 2018 Howard Rosenthal

C++ Classes & Object Oriented Programming

CSE 70 Final Exam Fall 2009

Friend Functions, Inheritance

Transcription:

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