0 - javarevisited

46
OOP Concepts Java Concepts Java Generics OOP and Java revisited Santiago Baldrich Universidad Nacional de Colombia [email protected] March 21, 2013 Santiago Baldrich OOP and Java revisited

Upload: -i

Post on 24-Oct-2015

16 views

Category:

Documents


1 download

DESCRIPTION

java Revisited

TRANSCRIPT

Page 1: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

OOP and Java revisited

Santiago Baldrich

Universidad Nacional de Colombia

[email protected]

March 21, 2013

Santiago Baldrich OOP and Java revisited

Page 2: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Objects

Real-world objects share two characteristics: They all have stateand behavior. Dogs have state (name, color, breed, hungry) andbehavior (barking, fetching, wagging tail).

What is a software object?

Software objects are conceptually similar to real-world objects:they too consist of state and related behavior. An object stores itsstate in fields (variables in some programming languages) andexposes its behavior through methods (functions in someprogramming languages).

Santiago Baldrich OOP and Java revisited

Page 3: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Methods

What is a method?

Methods operate on an object’s internal state and serve as theprimary mechanism for object-to-object communication. Hidinginternal state and requiring all interaction to be performed throughan object’s methods is known as data encapsulation, afundamental principle of object-oriented programming.

Santiago Baldrich OOP and Java revisited

Page 4: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Advantages of OOP

Modularity The source code for an object can be written andmaintained independently of the source code forother objects. Once created, an object can be easilypassed around inside the system.

Information-Hiding By interacting only with an object’s methods,the details of its internal implementation remainhidden from the outside world.

Santiago Baldrich OOP and Java revisited

Page 5: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Advantages of OOP

Code Re-use If an object already exists (perhaps written byanother software developer), you can use that objectin your program. This allows specialists toimplement/test/debug complex, task-specific objects,which you can then trust to run in your own code.

Plugability and debugging ease If a particular object turns out tobe problematic, you can simply remove it from yourapplication and plug in a different object as itsreplacement. This is analogous to fixing mechanicalproblems in the real world. If a bolt breaks, youreplace it, not the entire machine.

Santiago Baldrich OOP and Java revisited

Page 6: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Classes

What is a class?

Broadly speaking class is the blueprint from which individualobjects are created.

It contains fields and methods that all of its instances will have (orshare in some cases).

Santiago Baldrich OOP and Java revisited

Page 7: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Classes

Example (A Bicycle Class (1/2))

class Bicycle {

int cadence = 0;

int speed = 0;

int gear = 1;

void changeCadence(int newValue) {

cadence = newValue;

}

void changeGear(int newValue) {

gear = newValue;

}

}

Santiago Baldrich OOP and Java revisited

Page 8: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Classes

Example (A Bicycle Class (2/2))

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);

}

}

Santiago Baldrich OOP and Java revisited

Page 9: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Class Inheritance

Object-oriented programming allows classes to inherit commonlyused state and behavior from other classes.

Watch out...

In the Java programming language, each class is allowed to haveone direct superclass, and each superclass has the potential for anunlimited number of subclasses.

Santiago Baldrich OOP and Java revisited

Page 10: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Interfaces

What is an interface?

Interfaces form a contract between the class and the outside world,and this contract is enforced at build time by the compiler.

Watch out...

If your class claims to implement an interface, all methods definedby that interface must appear in its source code before the classwill successfully compile.

Santiago Baldrich OOP and Java revisited

Page 11: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Interfaces

Example (A Bicycle Interface)

interface Bicycle {

// wheel revolutions per minute

void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);

}

Santiago Baldrich OOP and Java revisited

Page 12: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

ObjectsClassesInterfaces

Java Concepts

Santiago Baldrich OOP and Java revisited

Page 13: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Declaring classes in Java

class MyClass extends MySuperClass

implements YourInterface {

// field, constructor, and

// method declarations

}

Santiago Baldrich OOP and Java revisited

Page 14: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

In general, class declarations can include these components, in order

Modifiers such as public, private, and a number of others that youwill encounter later.The class name, with the initial letter capitalized by convention.The name of the class’s parent (superclass), if any, preceded bythe keyword extends.A class can only extend (subclass) one parent.

Santiago Baldrich OOP and Java revisited

Page 15: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

A comma-separated list of interfaces implemented by theclass, if any, preceded by the keyword implements. A class canimplement more than one interface.

The class body, surrounded by braces, {}.

Santiago Baldrich OOP and Java revisited

Page 16: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Member Variables

There are several kinds of variables

Member variables in a classthese are called fields.

Variables in a method or block of code. These are called localvariables.

Variables in method declarations. These are called parameters.

Santiago Baldrich OOP and Java revisited

Page 17: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Field declarations are composed of three components, in order

Zero or more modifiers, such as public or private.

The field’s type.

The field’s name.

Santiago Baldrich OOP and Java revisited

Page 18: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Access modifiers

The first (left-most) modifier used lets you control what otherclasses have access to a member field. For the moment, consideronly public and private. Other access modifiers will be discussedlater.

public modifier the field is accessible from all classes.

private modifier the field is accessible only within its own class.

Santiago Baldrich OOP and Java revisited

Page 19: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Encapsulation

In the spirit of encapsulation, it is common to make fields private.This means that they can only be directly accessed from within thesame class. We still need access to these values, however. This canbe done indirectly by adding public methods that obtain the fieldvalues for us.

Santiago Baldrich OOP and Java revisited

Page 20: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Constructors

Constructors are called during object instantiation process, theserve as a way of initializing objects properly. Constructors aredefined as a ”no return type” method which may or may not takearguments.

Santiago Baldrich OOP and Java revisited

Page 21: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Example (Bicycle class (1/3))

public class Bicycle {

private int cadence;

private int gear;

private int speed;

public Bicycle(int startCadence, int startSpeed,

int startGear) {

gear = startGear;

cadence = startCadence;

speed = startSpeed;

}

public int getCadence() {

return cadence;

}

Santiago Baldrich OOP and Java revisited

Page 22: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Example (Bicycle class (2/3))

(...)

public void setCadence(int newValue) {

cadence = newValue;

}

public int getGear() {

return gear;

}

public void setGear(int newValue) {

gear = newValue;

}

public int getSpeed() {

return speed;

}

Santiago Baldrich OOP and Java revisited

Page 23: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Example (Bicycle class (3/3))

(...)

public void applyBrake(int decrement) {

speed -= decrement;

}

public void speedUp(int increment) {

speed += increment;

}

}

Santiago Baldrich OOP and Java revisited

Page 24: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Constructing objects

Object construction is generally comprised by three phases:

Declaration

Instantiation

Initialization

Example (Instantiation of a Bicycle object)

Bicycle bike = new Bicycle(10, 10, 1);

Santiago Baldrich OOP and Java revisited

Page 25: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Defining Methods

Example

public double calculateAnswer(double wingSpan,

int numberOfEngines, double length, double grossTons){

//do the calculation here

}

Santiago Baldrich OOP and Java revisited

Page 26: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

The this keyword

Within an instance method or a constructor, this refers to thecurrent object; this is, the object whose method or constructor isbeing called.

Santiago Baldrich OOP and Java revisited

Page 27: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Example (Using this with a field)

public class Point {

public int x = 0;

public int y = 0;

//constructor

public Point(int x, int y) {

this.x = x;

this.y = y;

}

}

Santiago Baldrich OOP and Java revisited

Page 28: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Example (Using this with a constructor)

public class Rectangle {

private int x, y;

private int width, height;

public Rectangle() {

this(0, 0, 0, 0);

}

public Rectangle(int width, int height) {

this(0, 0, width, height);

}

public Rectangle(int x, int y, int width, int height) {

this.x = x;

this.y = y;

this.width = width;

this.height = height;

}

...

}

Santiago Baldrich OOP and Java revisited

Page 29: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Exercise

1 Create a class Figure with fields/methods common to allfigures. Create two subclasses and specialize them with atleast one more method and field. Remember to follow theencapsulation principle.

2 Create an interface for class Figure and make sure toimplement its methods.

3 Override the default constructor from any of your classesadding default values using the this keyword for objectinstantiation.

4 Investigation: What is {time|space} complexity of analgorithm?

Santiago Baldrich OOP and Java revisited

Page 30: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Declaring classesMember VariablesAccess ModifiersConstructorsConstructing objectsDefining MethodsThis keywordJava Concepts Exercise

Java Generics

Santiago Baldrich OOP and Java revisited

Page 31: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Java generics

Why use Generics?

In a nutshell, generics enable types (classes and interfaces) to beparameters when defining classes, interfaces and methods. Muchlike the more familiar formal parameters used in methoddeclarations, type parameters provide a way for you to re-use thesame code with different inputs. The difference is that the inputsto formal parameters are values, while the inputs to typeparameters are types.

Santiago Baldrich OOP and Java revisited

Page 32: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Java generics

Code that uses generics has various benefits over non-generic code

Stronger type checks at compile-time A Java compiler appliesstrong type checking to generic code and issueserrors if the code violates type safety. Fixingcompile-time errors is easier than fixing runtimeerrors, which can be difficult to find.

Enabling programmers to implement generic algorithms By usinggenerics, programmers can implement genericalgorithms that work on collections of different types,can be customized, and are type safe and easier toread.

Santiago Baldrich OOP and Java revisited

Page 33: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Elimination of casts The following code snippet without genericsrequires casting:

List list = new ArrayList();

list.add("hello");

String s = (String) list.get(0);

When re-written to use generics, the code does notrequire casting:

List<String> list = new ArrayList<String>();

list.add("hello");

String s = list.get(0); // no cast

Santiago Baldrich OOP and Java revisited

Page 34: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Generic Type

A generic type is a generic class or interface that is parameterizedover types.

Example (a simple Box class (What could go wrong?))

public class Box {

private Object object;

public void set(Object object) {

this.object = object;

}

public Object get() { return object; }

}

Santiago Baldrich OOP and Java revisited

Page 35: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Generic class definition

A generic class is defined with the following format:

class name<T1, T2, ..., Tn> { /* ... */ }

The type parameter section, delimited by angle brackets (<>),follows the class name. It specifies the type parameters (also calledtype variables) T1, T2, ..., and Tn.

Example (a Generic version of the Box class)

public class Box<T> {

// T stands for "Type"

private T t;

public void set(T t) { this.t = t; }

public T get() { return t; }

} Santiago Baldrich OOP and Java revisited

Page 36: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Naming Conventions

By convention, type parameter names are single, uppercase letters.The most commonly used type parameter names are:

E - Element

K - Key

N - Number

T - Type

V - Value

S,U,V etc.- 2nd, 3rd, 4th types

You’ll see these names used throughout the Java SE API and therest of this lesson

Santiago Baldrich OOP and Java revisited

Page 37: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Bounded type parameters

Bounded type params

There may be times when you want to restrict the types that canbe used as type arguments in a parameterized type. For example, amethod that operates on numbers might only want to acceptinstances of Number or its subclasses. This is what bounded typeparameters are for.

Santiago Baldrich OOP and Java revisited

Page 38: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Example (Our box class with bounded type params (1/2))

public class Box<T> {

private T t;

public void set(T t) {

this.t = t;

}

public T get() {

return t;

}

public <U extends Number> void inspect(U u){

System.out.println("T: " + t.getClass().getName());

System.out.println("U: " + u.getClass().getName());

}

Santiago Baldrich OOP and Java revisited

Page 39: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Example (Our box class with bounded type params (2/2))

(...)

public static void main(String[] args) {

Box<Integer> integerBox = new Box<Integer>();

integerBox.set(new Integer(10));

integerBox.inspect("some text");

// error: this is still String!

}

}

Santiago Baldrich OOP and Java revisited

Page 40: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Multiple Bounds

The preceding example illustrates the use of a type parameter witha single bound, but a type parameter can have multiple bounds:

<T extends B1 & B2 & B3>

A type variable with multiple bounds is a subtype of all the typeslisted in the bound. If one of the bounds is a class, it must bespecified first. For example:

Class A { /* ... */ }

interface B { /* ... */ }

interface C { /* ... */ }

class D <T extends A & B & C> { /* ... */ }

Santiago Baldrich OOP and Java revisited

Page 41: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Wildcards

In generic code, the question mark (?), called the wildcard,represents an unknown type. The wildcard can be used in a varietyof situations: as the type of a parameter, field, or local variable;sometimes as a return type (though it is better programmingpractice to be more specific).wildcard is never used as a type argument for a generic methodinvocation, a generic class instance creation, or a supertype.

Santiago Baldrich OOP and Java revisited

Page 42: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Upper bounded wildcards

You can use an upper bounded wildcard to relax the restrictions ona variable. For example, say you want to write a method thatworks on List<Integer>, List<Double>, and List<Number>; youcan achieve this by using an upper bounded wildcard.

Santiago Baldrich OOP and Java revisited

Page 43: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Upper bounded wildcards

To declare an upper-bounded wildcard, use the wildcard character(’?’), followed by the extends keyword, followed by its upperbound.

Example (upper bounding a wildcard)

public static void process(List<? extends Foo> list) {

for (Foo elem : list) {

// ...

}

}

Santiago Baldrich OOP and Java revisited

Page 44: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Lower bounded wildcards

In a similar way to upper bounded wildcards, a lower boundedwildcard restricts the unknown type to be a specific type or a supertype of that type.

Lower bounded wildcards

lower bounded wildcard is expressed using the wildcard character(’?’), following by the super keyword, followed by its lower bound:<? super A>.

Santiago Baldrich OOP and Java revisited

Page 45: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

References

Oracle’s The Java Tutorials.

http://docs.oracle.com/javase/tutorial/java/

Santiago Baldrich OOP and Java revisited

Page 46: 0 - JavaRevisited

OOP ConceptsJava ConceptsJava Generics

Questions?

Santiago Baldrich OOP and Java revisited