Slide 1

Slide 1 text

Object Oriented Programming with Java Jussi Pohjolainen

Slide 2

Slide 2 text

OO CONCEPTS

Slide 3

Slide 3 text

Intro to OO • Object Orientated programming is a programming paradigm. • One way of describing the structure of the application • Several paradigms available. – Procedural, Functional, ... • OO is nowdays one of the most popular. – C++ – Java – C# – PHP 5 – ...

Slide 4

Slide 4 text

Benefits • Reusability – Once you written code, you can reuse it! • Management – Application is programmed using classes and objects. Pieces that communicate with each other. • Maintanence – When changing the code, it does not influence the whole application.

Slide 5

Slide 5 text

Basic Concept: Object • In real life, the world consists of objects: – cars, buildings, trees, ships, humans, flowers.. • Every object has actions (=methods!) that can incluence other objects – jack drives ferrari. – Object jack has a method drive that influences some way to object ferrari. – jack.drive(ferrari); • In OO, you should implement the app so that it consists of objects that influence each other!

Slide 6

Slide 6 text

Example about an Object • Datsun 100A is an object • Datsun 100A has different actions or methods: drive, brake, park... • Datsun 100A has information or attributes: color, amount of gears, amount of doors...

Slide 7

Slide 7 text

Basic Concept: Class • Class is a blueprint or template of an object • Class describes the state and behaviour to it's objects. • Object is created from the class.

Slide 8

Slide 8 text

Example about an Class • If Datsun 100A is an object, Car is a class. • If one wants to create Datsun 100A, you have to have first the blueprints of the Datsun. • Blueprints of an object: Class • Class Car -> Object Datsun 100A

Slide 9

Slide 9 text

Examples: Class to Object Class Object Car datsun 100a Human Jack Bauer Color red Laptop MacBook Pro String "some string" Array {1,2,3,2,4} ... ...

Slide 10

Slide 10 text

Class and Object • Car - class Datsun 100A Lamborghini Diablo Peugeot 406

Slide 11

Slide 11 text

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?

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

Car's Blueprint (Class) in UML Car brand motor amountOfDoors color hasFuzzyDices . .

Slide 14

Slide 14 text

From Class to Object datsun Datsun 100A 1.0 3 red true lambo Lamborghini Diablo 8.0 3 red false Car brand motor amountOfDoors color hasFuzzyDices . .

Slide 15

Slide 15 text

Car-class, extension Car brand motor amountOfDoors color hasFuzzyDices drive park brake

Slide 16

Slide 16 text

Class • Class is a template or blueprint to object • Class holds – Attributes (=variables) – Actions (=methods) • Class instances are called objects

Slide 17

Slide 17 text

CLASSES AND OBJECTS IN JAVA

Slide 18

Slide 18 text

Person Class to Objects george George Smith 40 Teacher 09-12345 Jack Jack Puupää Person firstname lastname age profession phonenumber eat sleep drinkBeer eat sleep drinkBeer

Slide 19

Slide 19 text

Person firstname lastname age profession phonenumber eat sleep drinkBeer Person – class to Java class Person { public String firstname; public String lastname; public int age; public String profession; public int phonenumber; public void eat() { System.out.println("Eating!"); } public void sleep() { System.out.println("Sleeping!"); } public void drinkBeer() { System.out.println("Drinking!"); } }

Slide 20

Slide 20 text

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;

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

Example: Car - class class Car { public String brand; public int amountOfGas; public void drive() { amountOfGas--; } }

Slide 23

Slide 23 text

Creating Objects From the Class class Car { .... } class JustTesting { public static void main(String [] args) { Car datsun = new Car(); datsun.amountOfGas = 100; datsun.drive(); System.out.println(datsun.amountOfGas); Car ferrari = new Car(); ferrari.amountOfGas = 300; ferrari.drive(); System.out.println(ferrari.amountOfGas); } }

Slide 24

Slide 24 text

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...

Slide 25

Slide 25 text

Example: Person - class class Person { private String name; private int weight; }

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

class Person { private String name; private int weight; public void setName(String n) { name = n; } public String getName() { return name; } public void setWeight(int w) { if(w > 0 && w <= 150) weight = w; } public int getWeight() { return 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()); } }

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

JAVA TYPES

Slide 30

Slide 30 text

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 ...

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

Differences • Primitive type – int a = 5; • Class type – int [] b= new int[5]; • b holds memory address • a holds value 5.

Slide 33

Slide 33 text

Memory Address? int [] b = new int[2]; b[0] = 1; b[1] = 2; // prints 0x01 System.out.println(b); RAM address value 0x01 1 0x02 2 address value 0x09 0x01 variable b

Slide 34

Slide 34 text

Memory Address? int [] b = new int[2]; b[0] = 1; b[1] = 2; int [] a = b; // prints 0x01 System.out.println(b); // prints 0x01 System.out.println(a); RAM address value 0x01 1 0x02 2 address value 0x09 0x01 variable b address value 0x19 0x01 variable a

Slide 35

Slide 35 text

Output? int [] b = new int[2]; b[0] = 1; b[1] = 2; int [] a = b; b[0] = 99; // Output? System.out.println(a[0]);

Slide 36

Slide 36 text

Differences Again • Primitive type – int a = 5; • Class type – int [] b= new int[5]; • b holds memory address • a holds value 5.

Slide 37

Slide 37 text

Differences Again • Primitive type – int a = 5; • Class type – Person jack = new Person() • jack holds memory address • a holds value 5.

Slide 38

Slide 38 text

Output? Person jack = new Person(); jack.setName("Jack Smith"); Person james = jack; james.setName("James Bond"); // output? System.out.println(jack.getName());

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

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.

Slide 42

Slide 42 text

String and Memory • String variables are objects => holds memory address. • Comparing contents – a.equals(b); • Comparing memory addresses – a == b

Slide 43

Slide 43 text

CONSTRUCTOR

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

Example class Car { public Car() { System.out.println("Constructor!"); } } class Test { public static void main(String [] args) { Car datsun = new Car(); } } > java Test Constructor!

Slide 46

Slide 46 text

class Car { private String brand; public Car(String b) { brand = b; } public String getBrand() { return brand; } } class Test { public static void main(String [] args) { Car datsun = new Car("Datsun 100A"); System.out.println( datsun.getBrand() ); } } > java Test Datsun 100A

Slide 47

Slide 47 text

Multiple Constructors class Car { public Car() { // Do something } public Car(String brand) { // Do something else } } class Test { public static void main(String [] args) { Car datsun = new Car(); Car ferrari = new Car("Ferrari"); } }

Slide 48

Slide 48 text

Problem? class Car { String brand; public Car(String brand) { brand = brand; } } class Test { public static void main(String [] args) { Car datsun = new Car("Datsun 100a"); } } > java Test null

Slide 49

Slide 49 text

Solution class Car { String brand; public Car(String brand) { this.brand = brand; } } class Test { public static void main(String [] args) { Car datsun = new Car("Datsun 100a"); } } > java Test Datsun 100a

Slide 50

Slide 50 text

COMPOSITION

Slide 51

Slide 51 text

Composition • Relatioship between objects, where one object owns, or has the other object • Car has or owns Motor • When Car is build, it's motor is built also • When Car is destroyed it's motor is destroyed

Slide 52

Slide 52 text

UML notation

Slide 53

Slide 53 text

Java: Composition // Composition class Car { private Motor motor; public Car() { motor = new Motor(); } }

Slide 54

Slide 54 text

One to Many?

Slide 55

Slide 55 text

Java: One to Many class Department { private Professor [] members; private int numberOfMembers; public Department(Professor prof) { members = new Professor[20]; members[0] = prof; numberOfMembers = 1; } public void addProfessor(Professor prof) { members[numberOfMembers] = prof; numberOfMembers++; } }

Slide 56

Slide 56 text

INHERITANCE

Slide 57

Slide 57 text

Introduction to Inheritance • Inheritance is a relationship between two or more classes where derived class inherites behaviour and attributes of pre-existing (base) classes • Intended to help reuse of existing code with little or no modification

Slide 58

Slide 58 text

Inheritance • Inheritance can be continous – Derived class can inherit another class, which inherits another class and so on – When changing the base class all the derived classes changes also • Example: – Mammal <– Human <– Worker <- Programmer • Could mammal be a derived class? If so, what would be the base class?

Slide 59

Slide 59 text

Picture about Inheritance a b Class A features: a,b c Class B Features: a,b,c d e Class C Features: a,b,d,e f Class D Features: a,b,d,e,f

Slide 60

Slide 60 text

Multiple Inheritance • In multiple inheritance a derived class has multiple base classes • C++ supports multiple base classes, Java don't Driver - license - Year of approval Conductor - Account number Taxi Driver - area House Boat Houseboat

Slide 61

Slide 61 text

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

Slide 62

Slide 62 text

Basic example • What are Programmer's attributes and methods? Human string name void sleep() void drink() void eat() Programmer int salary void implementApps() void beNerd()

Slide 63

Slide 63 text

Overriding? • What about now? Human string name void sleep() void drink() void eat() Programmer int salary void implementApps() void beNerd() void drink() void eat()

Slide 64

Slide 64 text

Overriding • Since programmer eats and drinks differently than humans (only Coke and Pizza) the eat and drink methods are overriden in Programmer!

Slide 65

Slide 65 text

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

Slide 66

Slide 66 text

Example <> Mammal string name void makesound() {abstract} Elephant int trunkLength makesound()

Slide 67

Slide 67 text

Example <> Figure int x, y double calculateArea() {abstract} Circle double radius double calculateArea() Rect double length, height double calculateArea()

Slide 68

Slide 68 text

INHERITANCE IN JAVA

Slide 69

Slide 69 text

Example: Basic Inheritance class Human { public void sleep() { System.out.println("Human sleeps"); } } class Programmer extends Human { } class Test { public static void main(String [] args) { Programmer jussi = new Programmer(); jussi.sleep(); // "Human sleeps" } }

Slide 70

Slide 70 text

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" } }

Slide 71

Slide 71 text

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(); } } > java Test Human sleeps Programmer sleeps

Slide 72

Slide 72 text

Constructors and Inheritance class Human { public Human() { 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(); } } > java Test Human Programmer

Slide 73

Slide 73 text

Constructors and Inheritance • Constructor allways calls the base classes constructor! • When creating a constructor void Human() { } • Java adds super() – call to it: void Human() { super(); // calls base classes constructor }

Slide 74

Slide 74 text

class Human { public Human() { 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(); } } > java Test Human Programmer

Slide 75

Slide 75 text

class Human { public Human() { super(); // Java adds this! Calls base classes contructor System.out.println("Human"); } } class Programmer extends Human { public Programmer() { super(); // Java adds this! Calls base classes contructor System.out.println("Programmer"); } } class Test { public static void main(String [] args) { Programmer jussi = new Programmer(); } } > java Test Human Programmer

Slide 76

Slide 76 text

What the...? What base class? class Human { public Human() { // Java adds this! Calls base classes contructor super(); System.out.println("Human"); } }

Slide 77

Slide 77 text

Object • Every class derives from a class called Object. // Java adds the extends Object too! class Human extends Object { public Human() { super(); System.out.println("Human"); } }

Slide 78

Slide 78 text

Object clone() equals() finalize() toString() ... Human String name ... http://java.sun.com/javase/6/docs/api/java/lang/Object.html

Slide 79

Slide 79 text

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(); } } > javac Test.java > DOES NOT COMPILE!!! Why?

Slide 80

Slide 80 text

class Human { public Human(int a) { System.out.println("Human"); } } class Programmer extends Human { public Programmer() { super(); // Java adds this and it calls constructor // Human() that does not exist.. System.out.println("Programmer"); } } class Test { public static void main(String [] args) { Programmer jussi = new Programmer(); } }

Slide 81

Slide 81 text

class Human { public Human(int a) { System.out.println("Human"); } } class Programmer extends Human { public Programmer() { super(5); // Now it works: Human(int a) exists. System.out.println("Programmer"); } } class Test { public static void main(String [] args) { Programmer jussi = new Programmer(); } }

Slide 82

Slide 82 text

class Human { private String name public Human(String name) { this.name = name; } } class Programmer extends Human { private int salary; public Programmer(String name, int salary) { super(name); this.salary = salary; } } class Test { public static void main(String [] args) { Programmer jussi = new Programmer("Jussi", 5000); } }

Slide 83

Slide 83 text

Abstract Class • From abstract class you cannot create objects! • Abstract class is usually used with inheritance • Abstract class may contain abstract methods. • Abstract method forces derived classes to implement the abstract method.

Slide 84

Slide 84 text

Abstract Class: example abstract class Mammal { abstract void makeSound(); } class Dog extends Mammal { // You have to implement this! public void makeSound() { System.out.println("Bark!"); } }

Slide 85

Slide 85 text

Abstract Class: example // Does NOT work, since Mammal is // abstract class Mammal object = new Mammal(); // Does work Dog spot = new Dog();

Slide 86

Slide 86 text

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

Slide 87

Slide 87 text

Abstract class to Interface abstract class Movable { abstract public void start(); abstract public void stop(); } ó interface Movable { public void start(); public void stop(); }

Slide 88

Slide 88 text

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 } }

Slide 89

Slide 89 text

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!

Slide 90

Slide 90 text

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 } }

Slide 91

Slide 91 text

POLYMORPHISM

Slide 92

Slide 92 text

int as parameter class Exercise13 { public static void main(String [] args) { int x = 4; myMethod(x); } public static void myMethod(int a) { } }

Slide 93

Slide 93 text

Human parameter class Human { } class Exercise13 { public static void main(String [] args) { Human jack = new Human(); myMethod(jack); } public static void myMethod(Human a) { } }

Slide 94

Slide 94 text

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) { } }

Slide 95

Slide 95 text

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) { } }

Slide 96

Slide 96 text

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? } }

Slide 97

Slide 97 text

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

Slide 98

Slide 98 text

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? } }

Slide 99

Slide 99 text

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