Java in A Nutshell
Java in A Nutshell
Benot Garbinato
Object-Oriented Programming
Any object-oriented Programming language should feature:
encapsulation inheritance polymorphism
Encapsulation (1)
Encapsulation is about distinguishing specification from implementations The specification expresses what all objects of some type are expected to do An implementation expresses how some objects of that type are doing it
Java in a Nutshell Benot Garbinato
Encapsulation (2)
In Java, a class defines both a specification (type) and an implementation of that specification In Java, an interface defines a pure specification It it thus impossible to instantiate (create an instance) 0f an interface One or more Java classes can implement a given interface
Java in a Nutshell Benot Garbinato
Inheritance (1)
Types and subtypes express specification relationships, i.e., relevant design relationships Classes and subclasses express implementation relationships and are irrelevant at the design level In Java, a class inheritance relationship defines both a subtype and a subclass relationship In Java, an interface inheritance relationship is merely a synonym of subtype relationship
Java in a Nutshell Benot Garbinato
Inheritance (2)
class inheritance ! subtyping " subclassing
Polymorphism (1)
Substitution Principle:
An object of some subtype of type T can be used wherever an object of type T is required
Vehicle v1 = new Vehicle(); Vehicle v2 = new Car(); Vehicle v3 = new Bicycle(); ... myScreen.drawInColor(v1); myScreen.drawInColor(v2); myScreen.drawInColor(v3); ...
Java in a Nutshell Benot Garbinato
Polymorphism (2)
Polymorphic variables can store objects of varying types The declared type of a variable is its static type The type of the object a variable refers is its dynamic type The Java compiler checks for static-type violations The Java runtime checks for dynamic-type violations
Car c = new Car(); Vehicle v = new Car();
Java in a Nutshell Benot Garbinato
Polymorphism (3)
Methods calls are also said to be polymorphic, meaning that the dynamic type of the variable rather than its static type determines the method to be called The method of the subclass is said to override the method of the superclass
class Vehicle { void print(){ System.out.println(I am a vehicle);} } class Bicycle extends Vehicle {} class Car extends Vehicle { void print(){ System.out.println(I am a car);} }
Vehicle v1 = new Vehicle(); Vehicle v2 = new Bicycle(); Vehicle v3 = new Car(); v1.print(); v2.print(); v3.print();
10
Polymorphism (4)
Vehicle v1
instance of
Vehicle
void print(){...}
Bicycle
Vehicle
void print(){...}
Car
void print(){...}
Vehicle
void print(){...}
:Car v3.print();
Java in a Nutshell Benot Garbinato
11
12
<HTML> <TITLE> Spot Applet </TITLE> <BODY> <APPLET CODE=Spot.class WIDTH=150 HEIGHT=150> </APPLET> </BODY> </HTML>
13
14
Development process
15
16
Questions?
17