You are on page 1of 46

OOP Concepts Java Concepts Java Generics

OOP and Java revisited


Santiago Baldrich
Universidad Nacional de Colombia santiago.baldrich@gmail.com

March 21, 2013

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

Objects
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (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 its state in elds (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages).

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

Methods

What is a method? Methods operate on an objects internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an objects methods is known as data encapsulation, a fundamental principle of object-oriented programming.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

Advantages of OOP

Modularity The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. Information-Hiding By interacting only with an objects methods, the details of its internal implementation remain hidden from the outside world.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

Advantages of OOP
Code Re-use If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specic objects, which you can then trust to run in your own code. Plugability and debugging ease If a particular object turns out to be problematic, you can simply remove it from your application and plug in a dierent object as its replacement. This is analogous to xing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
Santiago Baldrich OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

Classes

What is a class? Broadly speaking class is the blueprint from which individual objects are created. It contains elds and methods that all of its instances will have (or share in some cases).

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

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

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

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

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

Class Inheritance

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. Watch out... In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

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 dened by that interface must appear in its source code before the class will successfully compile.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

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

OOP Concepts Java Concepts Java Generics

Objects Classes Interfaces

Java Concepts

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

Declaring classes in Java

class MyClass extends MySuperClass implements YourInterface { // field, constructor, and // method declarations }

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

In general, class declarations can include these components, in order Modiers such as public, private, and a number of others that you will encounter later. The class name, with the initial letter capitalized by convention. The name of the classs parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. The class body, surrounded by braces, {}.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

Member Variables

There are several kinds of variables Member variables in a classthese are called elds. Variables in a method or block of code. These are called local variables. Variables in method declarations. These are called parameters.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

Field declarations are composed of three components, in order Zero or more modiers, such as public or private. The elds type. The elds name.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

Access modiers

The rst (left-most) modier used lets you control what other classes have access to a member eld. For the moment, consider only public and private. Other access modiers will be discussed later. public modier the eld is accessible from all classes. private modier the eld is accessible only within its own class.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

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

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

Constructors

Constructors are called during object instantiation process, the serve as a way of initializing objects properly. Constructors are dened as a no return type method which may or may not take arguments.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java 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

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java 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

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java 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

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java 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

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

Dening Methods
Example public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons){ //do the calculation here }

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

The this keyword

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

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

Example (Using this with a eld) 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

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java 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

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

Exercise
1

Create a class Figure with elds/methods common to all gures. Create two subclasses and specialize them with at least one more method and eld. Remember to follow the encapsulation principle. Create an interface for class Figure and make sure to implement its methods. Override the default constructor from any of your classes adding default values using the this keyword for object instantiation. Investigation: What is {time|space} complexity of an algorithm?
Santiago Baldrich OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Declaring classes Member Variables Access Modiers Constructors Constructing objects Dening Methods This keyword Java Concepts Exercise

Java Generics

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Java generics

Why use Generics? In a nutshell, generics enable types (classes and interfaces) to be parameters when dening classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with dierent inputs. The dierence is that the inputs to formal parameters are values, while the inputs to type parameters are types.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Java generics
Code that uses generics has various benets over non-generic code Stronger type checks at compile-time A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than xing runtime errors, which can be dicult to nd. Enabling programmers to implement generic algorithms By using generics, programmers can implement generic algorithms that work on collections of dierent types, can be customized, and are type safe and easier to read.
Santiago Baldrich OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Elimination of casts The following code snippet without generics requires casting: List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); When re-written to use generics, the code does not require casting: List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); // no cast

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Generic Type A generic type is a generic class or interface that is parameterized over 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

OOP Concepts Java Concepts Java Generics

Generic class denition A generic class is dened with the following format: class name<T1, T2, ..., Tn> { /* ... */ } The type parameter section, delimited by angle brackets (<>), follows the class name. It species the type parameters (also called type 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 }

OOP Concepts Java Concepts Java 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 Youll see these names used throughout the Java SE API and the rest of this lesson
Santiago Baldrich OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Bounded type parameters

Bounded type params There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java 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

OOP Concepts Java Concepts Java 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

OOP Concepts Java Concepts Java Generics

Multiple Bounds
The preceding example illustrates the use of a type parameter with a 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 types listed in the bound. If one of the bounds is a class, it must be specied rst. For example: Class A { /* ... */ } interface B { /* ... */ } interface C { /* ... */ } class D <T extends A & B & C> { /* ... */ }
Santiago Baldrich OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Wildcards

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, eld, or local variable; sometimes as a return type (though it is better programming practice to be more specic). wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Upper bounded wildcards

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

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Upper bounded wildcards To declare an upper-bounded wildcard, use the wildcard character ( ?), followed by the extends keyword, followed by its upper bound. Example (upper bounding a wildcard) public static void process(List<? extends Foo> list) { for (Foo elem : list) { // ... } }

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Lower bounded wildcards

In a similar way to upper bounded wildcards, a lower bounded wildcard restricts the unknown type to be a specic type or a super type 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

OOP Concepts Java Concepts Java Generics

References

Oracles The Java Tutorials. http://docs.oracle.com/javase/tutorial/java/

Santiago Baldrich

OOP and Java revisited

OOP Concepts Java Concepts Java Generics

Questions?

Santiago Baldrich

OOP and Java revisited

You might also like