Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala...

36
Some Historical Background ... Introduction to Java A (very) brief introduction to Object-Orientation Object-Oriented Programming in Java - Introduction and Overview - [email protected] University of Stirling November 9, 2012

Transcript of Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala...

Page 1: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Object-Oriented Programming in Java- Introduction and Overview -

[email protected]

University of Stirling

November 9, 2012

Page 2: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Outline

1 Some Historical Background . . .

2 Introduction to Java

3 A (very) brief introduction to Object-Orientation

Page 3: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

A Brief History of Software Development

1943 - Harvard Mark I. Programmed in assembly language(e.g. LD A,5) using punch cards.

1954 - John Backus invents FORTRAN, the first ”high level”programming language.

Late 1960s to early 1970s - Development of block-structuredlanguages such as PASCAL and C.

Mid 1980s - The Object-Oriented language C++ gainswidespread acceptance.

Page 4: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

A Brief History of Software Development (cont).

Early 1990s — Java emerges as a “write once, run anywhere”language for web applications, running on the Java VirtualMachine (JVM).

Mid 1990s to Mid 2000s — Object-Oriented development isboosted by practices such as Design Patterns, Aspect-Orientedprogramming, Agile programming and eXtreme programming.

Present day — Powerful scripting languages such as Groovyand Scala target the JVM.

Page 5: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Progress in Software Development

In the 1940s, a ‘large’ program might have 500 assemblylanguage instructions.

Using the structured techniques of the 1960’s, programs were‘manageable’ up to tens of thousands of lines.

Object-orientation has increased this to hundreds of thousands(and beyond).

Page 6: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Modularity is the key to progress . . .

The key principle that allows the creation of larger systems ismodularity.

A system is modular if it can be decomposed into black-boxes(modules) that are loosely-coupled.

A loosely-coupled system is one in which there are few pointsof communication between modules.

Page 7: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

How is modularity achieved?

Languages such as C attempt to achieve modularity by aprocedural decomposition of the problem: the modules arefunctions and they are connected by one function callinganother.

In languages such as Java, the modular units are objects.Objects have both data (a.k.a. attributes) and functions(a.k.a. methods).

Objects are connected by one object accessing an attribute or(preferably) a method of another object.

We will shortly see why the Object-Oriented approach isbetter for writing large programs.

Page 8: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Java is . . .

Object-Oriented

Interpreted — the Java compiler translates .java source intobytecode. The Java Virtual Machine (JVM) translatesbytecode into machine language and executes it.

Secure — The bytecode interpreter prevents intentional (orunintentional) sabotage of compiled programs.

Portable — Windows \Linux \MacOS \Solaris \OS2 etc

Page 9: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

A simple Java program

pub l i c c l a s s H e l l o W o r l d{

pub l i c s t a t i c void main ( S t r i n g [ ] a r g s ){

System . out . p r i n t l n ( ” H e l l o , World ” ) ;}

}

Java is case-sensitive, but whitespace insensitive.

main() is the entry point for the program, i.e. the point atwhich execution starts.

The body of the class and main functions are contained within{ and } symbols.

Every statement ends with a semi-colon.

Page 10: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Classes and Objects

A class represents a concept and an object is the physicalrealization of that concept.

Think of a class as a ‘factory’, i.e. a recipe for creating things.Objects are the things that the factory creates, e.g.:

Dog d = new Dog ( ” F ido ” ) ;d . bark ( ) ;

Page 11: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Introductory Example - The Car Class

Suppose you need to write a traffic simulation program thatanalyses the movement of cars.

Suppose each car has data such as speed, a maximumspeed and number plate.

In a procedural language, these might be represented with twofloating point variables and one string variable for each car.

In an Object-Oriented language they are all attributes of a Carobject.

Page 12: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Introductory Example - The Car Class

The UML Class diagram for Car looks like this:

The Java code corresponding to this UML is:

c l a s s Car {pub l i c S t r i n g numberPlate ;pub l i c double speed ;pub l i c double maxSpeed ;

}

These variables (numberPlate, speed and maxSpeed) arecalled member variables, instance variables, attributes orfields. An object is thus a specific instance of a class withparticular values for the fields.

Page 13: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Static and non-static members of a Class

The fields and methods of a class are collectively referred toas the members of the class.

A Java class can contain definitions for :

Static methods.Static fields.Instance methods.Instance fields.

Static methods\fields are associated with the class, not aparticular object.

By contrast, instance fields are part of every object.

Page 14: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Methods

Objects provide behavior as defined by the (non-static)methods of their class. The non-static methods are calledinstance or object methods and have access to the non-staticfields of an object.

For instance the Car class might have a method to make thecar go as fast as it can:

c l a s s Car {pub l i c S t r i n g numberPlate ;pub l i c double speed ;pub l i c double maxSpeed ;/∗∗ a c c e l e r a t e to maximum speed ∗/pub l i c void acce le rateToMax ( ) {

speed = maxSpeed ;}

}

Page 15: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Invoking Instance Methods

Outside the Car class, you call the accelerateToMax() methodin the same way as referencing fields, using the name of theobject you want to accelerate to maximum and the ‘.’separator:

c l a s s CarTest2 {pub l i c s t a t i c void main ( S t r i n g a r g s [ ] ) {

Car c = new Car ( ) ;c . numberPlate = ”P 123 XYZ” ;c . speed = 0 . 0 ;c . maxSpeed = 1 2 3 . 4 5 ;c . acce le rateToMax ( ) ;System . out . p r i n t l n ( c . numberPlate + ”

speed : ” + c . speed ) ;}

}

Page 16: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Invoking Instance Methods

The output is:

P 123 XYZ is moving at 123.45 kilometers per hour.

The accelerateToMax() method belongs to the Car class.

In constrast to procedural languages such as C, every methodin a Java program must be declared inside a class.

Page 17: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Analysis and Design

OO program design starts with an initial analysis phase:

We first identify concepts using the vocabulary of theproblem. This is known as the Problem Domain.

The idea is that the Problem Domain is relatively stable, sinceit corresponds closely to the real-world perspective of theend-user.

Page 18: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Analysis and Design (cont)

We then attempt to implement Problem Domain concepts insome programming language using algorithms and datastructures.

These programming concepts are in the Solution Domain.

There are clearly many possible ways that a concept in theproblem domain can be modelled in the solution domain.

The solution domain is therefore less stable than the problemdomain.

As we will see, abstraction is the key to stabilising thesolution.

Page 19: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Analysis and Design (cont)

For example, the concept Hill could be modelled by a2d-geometry, a 3d-mesh or a Gaussian distribution.

Which representation is the “right” one?

If we can come up with a suitable abstraction for Hill, we cansubstitute different representations without affecting theoverall behaviour of the program.

The requirements for this abstract description are dictated bythe problem domain.

Page 20: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Abstraction

We’ve said that the key to building a stable model isabstraction.

Abstraction allows us to form a view of a concept whichconsiders only necessary info and hides unnecessary detail.

Programming language design has seen a progression ofabstraction mechanisms . . .

Page 21: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Procedural Abstraction

Consider a function called power which raises one number tothe power of another:

/∗∗ Return x r a i s e d to th e power p ∗/double power ( double x , i n t p ) ;

We could change the implementation (perhaps make it moreefficient) and the code that invokes it won’t have to bechanged.

Page 22: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Data Abstraction

Each language provides a basic set of types (e.g. float, int,char in Java) and gives the user operations for manipulatingvariables of these types (e.g. +,-,* etc).

Data Abstraction takes the idea of abstraction further -instead of just defining operations, we can define our owndata types (e.g. records in Pascal, structs in C).

Data Abstraction allows the definition of new types, completewith a set of operations and methods, which can then be usedas if they were part of the language. We call these AbstractData Types (ADTs).

Page 23: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Object-Orientation

Object orientation takes data abstraction a step further viathe use of:

EncapsulationInheritancePolymorphism

We’ll look at these in more detail . . .

Page 24: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Aspects of OO – 1. Encapsulation

Encapsulation means that the internal details of an ADT (e.g.any data) should only be accessed via methods.

Restricting access to methods stops the state of the ADTfrom being modified in undesirable ways.

It also insulates the user from dependency on internal details(c.f. Y2K problem).

Page 25: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Encapsulation via Access Protection

Most OO languages including Java allow you to protect fieldsfrom external modification. This allows you to guarantee thatobjects are in a consistent state.

For example, inside the Car class we’d like to be confident thatthe speed can never be greater than the maximum speed, i.e.we want a way to make the following illegal:

Car c = new Car ( ) ;c . maxSpeed = 1 0 0 . 0 ;c . speed = 1 5 0 . 0 ; // Want to p r e v e n t t h i s !

This code violates the conceptual constraints of the class. Weideally want the compiler to enforce these constraints.

To achieve this, we can specify who will be allowed to accesswhich parts of the class.

Page 26: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Encapsulation in Practice

pub l i c c l a s s Car (pr i va te S t r i n g numberPlate ;pr i va te double speed ;pr i va te double maxSpeed ;pub l i c Car ( S t r i n g numberPlate , double maxSpeed ){

t h i s . numberPlate = numberPlate ;i f ( maxSpeed < 0 . 0 )

throw new I l l e g a l A r g u m e n t E x c e p t i o n ( ) ;t h i s . maxSpeed = maxSpeed ;

}pub l i c S t r i n g getNumberPlate ( ) { return

numberPlate ; }pub l i c double getMaxSpeed ( ) { return speed ; }pub l i c double getSpeed ( ) { return maxSpeed ; }

Page 27: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

The Benefits of Encapsulation

Encapsulation has three main benefits:

It allows you to enforce constraints on an object’s state.

It provides a simpler interface to the class. Users of the classdon’t need to know everything that’s in the class, only thepublic parts.

It separates interface from implementation, allowing them tovary independently. For instance, we could make thenumberPlate field of Car a NumberPlate class instead of aString .

Page 28: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Aspects of OO – 2. Polymorphism

Derives from the Greek word for “many forms”.

Is central to Object-orientation.

Encourages the creation of class hierarchies, in which familiesof behaviour are related by inheritance.

Page 29: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

The need for Polymorphism

Suppose that we now wish our traffic simulation to monitorthe environmental cost of different forms of transport. Inaddition to cars, we might also wish to include trains, planesand boats.

We can then experiment the tradeoff of journey time againstCO2 footprint.

Using polymorphism, we can create a framework for thesimulation by abstracting the key features that are common toall these forms of transport.

We start by noting that Car, Train, Plane and Boat are allexamples of the (abstract concept) Vehicle.

Page 30: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

1. Define the (abstract) superclass

We define Vehicle as an abstract class with methods forgetting the carbon footprint and max speed:

abstract c l a s s V e h i c l e {pub l i c abst ract double g et C O2 Fo o tp r in t ( ) ;pub l i c abst ract double getMaxSpeed ( ) ;

}

Page 31: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

2. Create subclasses...

We then create subclasses of Vehicle corresponding to each ofPlane, Car and Train:

c l a s s Plane extends V e h i c l e {pub l i c double g et C O2 Fo o tp r in t ( ) { /∗ . . . ∗/

}pub l i c double getMaxSpeed ( ) { /∗ . . . ∗/ }

}c l a s s Car extends V e h i c l e {

pub l i c double g et C O2 Fo o tp r in t ( ) { /∗ . . . ∗/}

pub l i c double getMaxSpeed ( ) { /∗ . . . ∗/ }}c l a s s T r a i n extends V e h i c l e {

pub l i c double g et C O2 Fo o tp r in t ( ) { /∗ . . . ∗/}

pub l i c double getMaxSpeed ( ) { /∗ . . . ∗/ }}

Page 32: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

3. Define the framework in terms of the superclass

Now that we have our Vehicle class hierarchy, we could definethe ‘greenest travel option’ between a source and destinationas a method that returns a list of Vehicles:

L i s t < V e h i c l e > g e t G r e e n e s t T r a v e l O p t i o n (LatLong from , LatLong to ) ;

We might similarly define a method for the ‘fastest traveloption’:

L i s t < V e h i c l e > g e t F a s t e s t T r a v e l O p t i o n ( LatLongfrom , LatLong to ) ;

Page 33: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

4. Using the Framework

We might use one of these methods as follows:

L i s t < V e h i c l e > v e h i c l e s =g e t G r e e n e s t T r a v e l O p t i o n ( LondonLatLong ,Dub l inLatLong ) ;

double tota lCO2Cost = 0 ;f o r ( V e h i c l e v : v e h i c l e s )

tota lCO2Cost += v . ge t CO 2 Fo o tp r i n t ( ) ;System . out . p r i n t l n ( ” t o t a l CO2 f o o t p r i n t o f

j o u r n e y : ” + tota lCO2Cost ) ;

Page 34: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Points to Note

The code above doesn’t need to know anything about thedifferent subclasses of Vehicle.

We are even free to add new subclasses of Vehicle (as long asthey provide meaningful implementations of the abstractmethods) and the framework code will continue to workunchanged.

This ability of existing framework code to remain compatiblewith new code is called the ‘Open-Closed Principle’ and is themost important aspect of Object-Orientation.

Page 35: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Some Reading . . .

“Thinking in Java” (Bruce Eckel)http://www.mindview.net/Books/TIJ/

Sun Java Tutorial: ttp://java.sun.com/docs/books/

tutorial/getStarted/index.html

Design Patterns in Java : http:

//www.patterndepot.com/put/8/JavaPatterns.htm

‘Object-Oriented Analysis and Design with Applications’ (2ndEdition) Grady Booch et al.

Page 36: Object-Oriented Programming in Java - Introduction …jsw/OO in Java - Introduction and...and Scala target the JVM. Some Historical Background ::: Introduction to JavaA (very) brief

Some Historical Background . . . Introduction to Java A (very) brief introduction to Object-Orientation

Acknowledgements

Thanks to Colin Higgins, who provided some of the original Java slides

that these have evolved from . . .