Object Orientated Programming With Java: Jussi Pohjolainen Tampere University of Applied Sciences
Object Orientated Programming With Java: Jussi Pohjolainen Tampere University of Applied Sciences
with Java
Jussi Pohjolainen
Tampere University of Applied Sciences
MOTIVATION
Job Opportunities?
Little acronyms from job descriptions:
S60, C++, J2ME, Java, Java EE, SCRUM, JAX-WS 2.0,
EJB 3.0, Spring, Hybernate, Struts, SQL, XHTML,
CSS, Symbian C++, Perl, PHP, Python, LDAP, MFC,
XML, .NET, Visual Basic, AJAX, Objective-C, JSP,
Servlet, GTK, Qt, JavaScript, Oracle, SQL Server, DB
Design
Where is Object Orientated programming?
Developing S60 apps?
S60
Symbian C++
OO skills
iPhone
Objective-C
OO skills
Java
Data Structures /DB UI programming Www-
technique
s: Xhtml,
OO skills CSS, XML
Class Object
Car datsun 100a
Human Jack Bauer
Color red
Laptop MacBook Pro
String "some string"
Array {1,2,3,2,4}
... ...
Class and Object
Car - class
Datsun 100A
Peugeot 406
Lamborghini Diablo
Car's Blueprint
When building a Car's blueprint (class), you
have to think that what is similar in all car's
So what is similar in datsun, lamborghini and
peugeot?
Objects datsun, lambo, peugeot
datsun:
brand: Datsun 100A , motor: 1.0, fuzzy
dices: yes, color: red
lambo
brand: Lamborghini Diablo, motor: 8.0,
fuzzy dices: no, color: punainen
peugeot
brand: Peugeot 406, motor: 2.2, fuzzy
dices: no, color: blue
Car's Blueprint (Class) in UML
Car
brand
motor
amountOfDoors
color
hasFuzzyDices
.
.
From Class to Object
datsun
Car
Datsun 100A
1.0
brand 3
motor red
amountOfDoors true
color
hasFuzzyDices lambo
.
. Lamborghini Diablo
8.0
3
red
false
Car-class, extension
Car
brand
motor
amountOfDoors
color
hasFuzzyDices
drive
park
brake
Class
Class is a template or blueprint to object
Class holds
Attributes (=variables)
Actions (=methods)
Class instances are called objects
CLASSES AND OBJECTS IN JAVA
Person Class to Objects
george
Person
George
Smith
firstname 40
lastname Teacher
age 09-12345
profession
phonenumber
eat
sleep
drinkBeer
eat
sleep
drinkBeer Jack
Jack
Person class to Java
class Person {
Person
public String firstname;
public String lastname;
public int age;
firstname public String profession;
lastname public int phonenumber;
age
profession public void eat() {
System.out.println("Eating!");
phonenumber }
public void sleep() {
System.out.println("Sleeping!");
}
public void drinkBeer() {
eat
System.out.println("Drinking!");
sleep }
drinkBeer }
From Class to Object
App always starts from the main-method
Let's test the Person class
This creates a variable a which type is integer
int a;
This creates a object jack which type is Person
Person jack;
From Class to Object
class Person {
....
}
class JustTesting {
public static void main(String [] args)
{
// Declare the object
Person jack;
// Initialize the object
jack = new Person();
jack.firstname = "Jack";
jack.lastname = "Smith";
jack.drinkBeer();
}
}
Example: Car - class
class Car
{
public String brand;
public int amountOfGas;
class JustTesting {
public static void main(String [] args)
{
Car datsun = new Car();
datsun.amountOfGas = 100;
datsun.drive();
System.out.println(datsun.amountOfGas);
public method
About Attributes
Attributes are usually marked as private
The reason for this is that other objects
cannot change the values as they will
You don't for example want that every object
in the world can change person's weight to
500kg...
Example: Person - class
class Person {
private String name;
private int weight;
}
class Person {
private String name;
private int weight;
}
class JustTesting {
public static void main(String [] args)
{
Person jack = new Person();
jack.name = "Jack Smith";
jack.weight = 500;
}
}
RESULT:
TB308POHJUS-L-2:temp pohjus$ javac Person.java
Person.java:9: name has private access in Person
jack.name = "Jack Smith";
^
Person.java:10: weight has private access in Person
jack.weight = 500;
^
2 errors
class Person {
private String name;
private int weight;
class JustTesting {
public static void main(String [] args)
{
Person jack = new Person();
jack.setName("Jack Smith");
jack.setWeight(200);
System.out.println(jack.getName());
}
}
Accessor and Mutator - methods
class Person {
private String name;
private int weight;
// Mutator
public void setName(String n) {
name = n;
}
// Accessor
public String getName() {
return name;
}
// Mutator
public void setWeight(int w) {
if(w > 0 && w <= 150)
weight = w;
}
// Accessor
public int getWeight() {
return weight;
}
}
JAVA TYPES
Java Types
Java has two type of types
1) Primitive types
byte, short, int, long, double, float, char, boolean
2) Class types
String, Scanner, Array, JButton, JFrame ...
Differences
Primitive types are spelled with lowercase:
int, double, float...
Class types are spelled with uppercase
String, Scanner, Person, Cat, Car ...
Primitive type declaring and initialization
int a = 5;
Class type declaring and initialization with
new
Dog spot = new Dog();
Differences
Primitive type
int a = 5;
Class type
int [] b= new int[5];
b holds memory address
a holds value 5.
Memory Address?
int [] b = new int[2]; RAM
variable b
b[0] = 1; address value
b[1] = 2; 0x09 0x01
// prints 0x01
System.out.println(b);
address value
0x01 1
0x02 2
Memory Address?
int [] b = new int[2]; RAM
variable b
b[0] = 1; address value
variable a
b[1] = 2; address value 0x09 0x01
// prints 0x01
address value
System.out.println(b); 0x01 1
// prints 0x01 0x02 2
System.out.println(a);
Output?
int [] b = new int[2];
b[0] = 1;
b[1] = 2;
int [] a = b;
b[0] = 99;
// Output?
System.out.println(a[0]);
Differences Again
Primitive type
int a = 5;
Class type
int [] b= new int[5];
b holds memory address
a holds value 5.
Differences Again
Primitive type
int a = 5;
Class type
Person jack = new Person()
jack holds memory address
a holds value 5.
Output?
Person jack = new Person();
jack.setName("Jack Smith");
Person james = jack;
james.setName("James Bond");
// output?
System.out.println(jack.getName());
Methods and Variables
public void method(int x) {
x++;
}
public void main(String [] args) {
int y = 3;
method(y);
// Output is 3!
System.out.println(y);
}
Methods and Variables
public void method(int [] x) {
x[0] = 12;
}
public void main(String [] args) {
int [] y = {1,2,3};
method(y);
// Output is 12 since array is class type!
System.out.println(y[0]);
}
String
String is an exception to the rules
String is a class type that acts like primitive
type
String is the only class type that can be
initialized without the new word.
String a = "hello";
String is passed by value in methods, so String
is copied when moving strings in methods.
String and Memory
String variables are objects => holds memory
address.
Comparing contents
a.equals(b);
Comparing memory addresses
a == b
CONSTRUCTOR
Constructors
Constructor is a init method that is called
when an object is created
Java provides default constructor (=
constructor with no parameters)
Constructor has the same name than the class
Constructor does not return anything
Constructor usually initalizes class members
Example
class Car {
public Car() {
System.out.println("Constructor!");
}
}
class Test {
public static void main(String [] args) {
Car datsun = new Car();
}
}
public Car() {
motor = new Motor();
}
}
One to Many?
Java: One to Many
class Department
{
private Professor [] members;
private int numberOfMembers;
Class A
Class B Class C
Features: a,b,d,e,f
f
Class D
Multiple Inheritance
In multiple inheritance a derived class has
multiple base classes
C++ supports multiple base classes, Java don't
Driver Conductor
- license - Account number
House Boat - Year of approval
Taxi Driver
Houseboat - area
Inheritance and Capsulation
private
Is accessible only via the base class
public
Is accessible everywhere (base class, derived class,
othe classes)
protected
Is accessible by the base class and derived classes
Basic example
What are Programmer's attributes and
methods?
Human
Programmer
string name
int salary
void sleep()
void implementApps()
void drink()
void beNerd()
void eat()
Overriding?
What about now?
Human
Programmer
string name
int salary
void sleep()
void drink() void implementApps()
void eat() void beNerd()
void drink()
void eat()
Overriding
Since programmer eats and drinks differently
than humans (only Coke and Pizza) the eat
and drink methods are overriden in
Programmer!
Abstract Class
Abstract class is a class which you cannot
instantiate (create objects)
You can inherit abstract class and create
objects from the inherited class, if it is
concrete one
Abstract class in C++ has abstract methods,
that do not have implementations
These methods forces derived classes to
implement those methods
Example
<<abstract>>
Mammal
string name
Elephant
int trunkLength
makesound()
Example
<<abstract>>
Figure
int x, y
Circle Rect
}
class Test {
public static void main(String [] args) {
Programmer jussi = new Programmer();
jussi.sleep(); // "Human sleeps"
}
}
Example: Overriding
class Human {
public void sleep() {
System.out.println("Human sleeps");
}
}
class Programmer extends Human {
public void sleep() {
System.out.println("Programmer sleeps");
}
}
class Test {
public static void main(String [] args) {
Programmer jussi = new Programmer();
jussi.sleep(); // "Programmer sleeps"
}
}
Example: super
class Human {
public void sleep() {
System.out.println("Human sleeps");
}
}
class Programmer extends Human {
public void sleep() {
super.sleep();
System.out.println("Programmer sleeps");
}
}
class Test {
public static void main(String [] args) {
Programmer jussi = new Programmer();
jussi.sleep();
}
}
clone()
equals()
finalize()
toString()
...
Human
String name
...
http://java.sun.com/javase/6/docs/api/java/lang/Object.html
class Human {
public Human(int a) {
System.out.println("Human");
}
}
class Programmer extends Human {
public Programmer() {
System.out.println("Programmer");
}
}
class Test {
public static void main(String [] args) {
Programmer jussi = new Programmer();
}
}
// Does work
Dog spot = new Dog();
Java: Abstract class and Interface
Abstract class can hold "normal" methods and
abstract methods.
Interface holds only abstract methods
Abstract class:
class A extends someAbstractClass
Interface
class A implements someInterface
Abstract class to Interface
abstract class Movable {
abstract public void start();
abstract public void stop();
}
interface Movable {
public void start();
public void stop();
}
Implementing the Interface
interface Movable {
public void start();
public void stop();
}
class Car implements Movable {
// You have to implement these
public void start() {
// Do something
}
public void stop() {
// Do something
}
}
Abstract class vs Interface
Abstract class can hold normal methods and
abstract methods
Interface can hold only abstract methods
Class can inherite only one base class
Class can implement several interfaces!
class Car extends Vehicle implements Movable,
RunsOnGasoline {
// You have to implement these
public void start() {
// Do something
}
public void stop() {
// Do something
}
public void reduceGasoline() {
// Do something
}
public void addGasoline() {
// Do something
}
}
POLYMORPHISM
int as parameter
class Exercise13 {
public static void main(String [] args) {
int x = 4;
myMethod(x);
}
public static void myMethod(int a) {
}
}
Human parameter
class Human {
}
class Exercise13 {
public static void main(String [] args) {
Human jack = new Human();
myMethod(jack);
}
public static void myMethod(Human a) {
}
}
Mammal parameter
class Mammal {
}
class Human extends Mammal {
}
class Dog extends Mammal {
}
class Exercise13 {
public static void main(String [] args) {
Human jack = new Human();
Dog spot = new Dog();
Mammal mammal = new Mammal();
// these work! You can pass mammals, dogs and humans to the method!
myMethod(jack);
myMethod(dog);
myMethod(mammal);
}
public static void myMethod(Mammal a) {
}
}
Object parameter
...
class Exercise13 {
public static void main(String [] args) {
Human jack = new Human();
Dog spot = new Dog();
Mammal mammal = new Mammal();
// these work! You can pass every object to the
method
myMethod(jack);
myMethod(dog);
myMethod(mammal);
myMethod("hello"); // String
}
public static void myMethod(Object a) {
}
}
Calling methods from Mammal
class Mammal {
}
class Human extends Mammal {
public void bark() { System.out.println("Bark!"); };
}
class Dog extends Mammal {
}
class Exercise13 {
public static void main(String [] args) {
Human jack = new Human();
Dog spot = new Dog();
Mammal mammal = new Mammal();
myMethod(jack);
myMethod(dog);
myMethod(mammal);
}
public static void myMethod(Mammal a) {
a.bark(); // Why this does not work?
}
}
Solution
class Exercise13 {
public static void main(String [] args) {
Human jack = new Human();
Dog spot = new Dog();
Mammal mammal = new Mammal();
myMethod(jack);
myMethod(dog);
myMethod(mammal);
}
public static void myMethod(Mammal a) {
// Now it works
if(a instanceof Dog) {
Dog spot = (Dog) a;
spot.bark();
}
}
}
This works, why?
class Mammal {
public void giveBirth() { System.out.println("Giving birth"); };
}
class Human extends Mammal {
}
class Dog extends Mammal {
}
class Exercise13 {
public static void main(String [] args) {
Human jack = new Human();
Dog spot = new Dog();
Mammal mammal = new Mammal();
myMethod(jack);
myMethod(dog);
myMethod(mammal);
}
public static void myMethod(Mammal a) {
a.giveBirth(); // Why this works?
}
}
class Movable {
public void start();
public void stop();
}
class Vehicle {
}
class Car extends Vehicle implements Movable {
public void start() {
// Do something
}
public void stop() {
// Do something
}
}
class Exercise13 {
public static void main(String [] args) {
Car c = new Car();
myMethod(c);
}
// You can pass every object that implements the Movable!
public static void myMethod(Movable a) {
a.start();
}
}