Java for OOP Objects de-mystified Christoph Angerer Java Virtual - - PowerPoint PPT Presentation

java for oop
SMART_READER_LITE
LIVE PREVIEW

Java for OOP Objects de-mystified Christoph Angerer Java Virtual - - PowerPoint PPT Presentation

Java for OOP Objects de-mystified Christoph Angerer Java Virtual Machine VM Heap Program Memory (Program Code (Classes, JIT Memory) etc.) Reads Internal use Virtual Machine Slide 2 Runtime Model public class BankAccount {


slide-1
SLIDE 1

Java for OOP

Objects de-mystified Christoph Angerer

slide-2
SLIDE 2

Slide

Java Virtual Machine

2

Program Code Heap

(Program Memory)

VM Memory

(Classes, JIT etc.)

Virtual Machine

Reads Internal use

slide-3
SLIDE 3

Slide

Runtime Model

3

public class BankAccount { private int balance; public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } public void deposit(int amount) { /* some code */ } public int withdraw(int amount) { /* some code */ } }

class balance 42 Object a3249 3249 getBalance {code} setBalance {code} deposit {code} withdraw {code} super name methodTable Class BankAccount nkAccount “BankAccount” super null name methodTable Class Object bject hashCode {code} toString {code} ... ... “Object”

(*) the bank account example is taken from the Java in Depth class from Carlo A. Furia

slide-4
SLIDE 4

Slide

getBalance {code} setBalance {code} deposit {code} withdraw {code} super name methodTable Class BankAccount nkAccount “BankAccount” class balance 42 Object a3249 3249 super null name methodTable Class Object bject hashCode {code} toString {code} ... ... “Object”

How To: Method Call

4

BankAccount myAccount = ...; int myBalance = myAccount.getBalance();

(1) (2) (3) (4) this-pointer

slide-5
SLIDE 5

Slide

getBalance {code} setBalance {code} deposit {code} withdraw {code} super name methodTable Class BankAccount nkAccount “BankAccount” class balance 42 Object a3249 3249 super null name methodTable Class Object bject hashCode {code} toString {code} ... ... “Object”

How To: Method Call 2

5

BankAccount myAccount = ...; String myDescr = myAccount.toString();

(1) (2) (3) (6) this-pointer (4) (5)

slide-6
SLIDE 6

Slide

Fundamental Concepts

6

  • Method Call/Dispatching: starting from the object,

follow its class and superclass pointers until a method is found in a method table

slide-7
SLIDE 7

Slide

getBalance {code} setBalance {code} toString {code} deposit {code} super name methodTable Class BankAccount nkAccount “BankAccount” class balance 42 Object a3249 3249 super null name methodTable Class Object bject hashCode {code} toString {code} ... ... “Object”

How To: Overriding

7

(1) (2) (3)

public class BankAccount { /*...*/ public String toString() { return “I am a bank account”; } } String myDescr = myAccount.toString();

  • verridden
slide-8
SLIDE 8

Slide

Fundamental Concepts

8

  • Method Call/Dispatching: starting from the object,

follow its class and superclass pointers until a method is found in a method table

  • Overriding: a subclass defines a method with the

same name as a superclass so it is found first

slide-9
SLIDE 9

Slide

How To: Overloading

9

deposit {code} deposit {code} ... ... super name methodTable Class BankAccount nkAccount “BankAccount” class balance 42 Object a3249 3249 super null name methodTable Class Object bject hashCode {code} toString {code} ... ... “Object”

(1) (2) (3) ?

We need more information to resolve this

public class BankAccount { /*...*/ public void deposit(int amount) { /* some code */ } public void deposit(float amount) { /* some code */ } } myAccount.deposit(42.56);

slide-10
SLIDE 10

Slide

How To: Overloading 2

10

deposit(int) {code} deposit(float) {code} ... ... super name methodTable Class BankAccount nkAccount “BankAccount” class balance 42 Object a3249 3249 super null name methodTable Class Object bject hashCode {code} toString {code} ... ... “Object”

(2) (3)

public class BankAccount { /*...*/ public void deposit(int amount) { /* some code */ } public void deposit(float amount) { /* some code */ } } myAccount.deposit(42.56);

(1)

slide-11
SLIDE 11

Slide

Fundamental Concepts

11

  • Method Call/Dispatching: starting from the object,

follow its class and superclass pointers until a method is found in a method table

  • Overriding: a subclass defines a method with the

same name as a superclass so it is found first

  • Overloading: Java allows us to use the same name

for different methods as long as the parameter types are different (overloading is essentially syntactic sugar!)

slide-12
SLIDE 12

Slide

getBalance {code} setBalance {code} toString {code} deposit {code} super name methodTable Class BankAccount nkAccount “BankAccount” class balance 42 Object a3249 3249 super null name methodTable Class Object bject hashCode {code} toString {code} ... ... “Object”

How To: call to this

12

(1) (2) (3)

public class BankAccount { /*...*/ public String toString() { return “I am a bank account with ” + this.getBalance() + “ CHF”; } } String myDescr = myAccount.toString();

(4) this-pointer (6) (5)

slide-13
SLIDE 13

Slide

getBalance {code} setBalance {code} toString {code} deposit {code} super name methodTable Class BankAccount nkAccount “BankAccount” class balance 42 Object a3249 3249 super null name methodTable Class Object bject hashCode {code} toString {code} ... ... “Object”

How To: call to super

13

(1) (2) (3)

public class BankAccount { /*...*/ public String toString() { return super.toString() + “ (I am a bank account)”; } } String myDescr = myAccount.toString();

(4) this-pointer (5)

slide-14
SLIDE 14

Slide

Fundamental Concepts

14

  • Method Call/Dispatching: starting from the object,

follow its class and superclass pointers until a method is found in a method table

  • Overriding: a subclass defines a method with the

same name as a superclass so it is found first

  • Overloading: Java allows us to use the same name

for different methods as long as the parameter types are different (overloading is essentially syntactic sugar!)

  • Super-call: similar to a method call to ‘this’, but

method resolution starts at the super class

slide-15
SLIDE 15

Slide

Classes re-visited

  • A class is a collection of:
  • fields
  • methods, including signatures and bodies
  • one class can extend another (“inherit from”):
  • sets the ‘super’ pointer to the other class
  • An object “is an instance of a class”:
  • Its ‘class’ pointer points to the class struct
  • the fields defined in the class define the size and

layout of the object struct

15

slide-16
SLIDE 16

Slide

Multiple Inheritance

  • What if: the single ‘super’

pointer were a list of pointers?

  • How to resolve methods now?

What order?

  • Different solutions, no “right”

strategy, weird corner cases

  • Java’s Solution: don’t allow it
  • ⇒ Single inheritance +

Interfaces

16

super name ... methodTable ... Class A super name ... methodTable ... Class B super name ... methodTable ... Class C super name ... methodTable ... Class D

slide-17
SLIDE 17

Slide

Java Interfaces

  • “classes with empty method bodies”
  • An interface defines method signatures that classes

later implement

  • Because an interface does not include method

bodies, multiple inheritance is not a problem

  • An Interface can extend other interfaces
  • Interfaces are interesting for structuring your code

and modeling

  • But don’t play a big role at runtime during execution

17

slide-18
SLIDE 18

Slide

Abstract Classes

  • Mix between interfaces and classes (“incomplete classes”)
  • A class can leave methods unimplemented and only define

the signature if it is declared to be abstract

  • Children of this class must either implement all abstract

methods or be declared abstract itself

  • Abstract classes can contain method implementations:
  • We still have problems with multiple inheritance
  • Therefore: A class can only extend exactly one other

class or abstract class

  • Again: more interesting for designing than at runtime

18

slide-19
SLIDE 19

Slide 19

public abstract class BankAccount { /*code as before, plus:*/ public abstract float getInterestRate(); } interface Freezable { void freeze(); void unfreeze(); } interface Updatable { void dailyUpdate(Date d); } public class PrivatePersonAccount

  • extends BankAccount

implements Freezable, Updatable { boolean isFrozen = false; void freeze() { this.isFrozen = true; } void unfreeze() { this.isFrozen = false; } void dailyUpdate(Date d) { if(! this.isFrozen) { /* compute interest */ } } void getInterestRate() { return DB.getPrivatePersonInterestRate(); } }

Interface Example

slide-20
SLIDE 20

Slide

Code Management

20

  • Java provides many features for managing code:
  • Packages
  • Visibility modifiers (public, protected, package-

local, private)

  • Those features are not terribly important for the

program execution, but in Java you still have to understand them (somewhat)

slide-21
SLIDE 21

Slide

Packages

  • In big projects, one has to deal with naming conflicts (what class

“Person” do you mean?)

  • Java avoids this through packages (a.k.a. “really long names”)
  • by convention in reverse URL notation:

com.mydomain.myproject.some.package

  • but that’s not necessary and has nothing to do with internet

URLs

  • In a file, you can either write this really long name everywhere
  • or import a class or a whole package in the beginning of the file
  • as long as you don’t get a naming conflict; then you have to use

some fully qualified names again

  • For defining your own packages, consult the internet

21

slide-22
SLIDE 22

Slide 22

//put MyClass into this package //(make sure to also use the right folder com/mydomain/projectA) package com.mydomain.projectA; import java.util.List; //import the single class List import java.util.concurrent.*; //import the whole package public class MyClass { void doStuff() { //List is the java.util.List; other lists must be fully named com.mydomain.utils.List myList = new com.mydomain.utils.List(10);

  • List javaList = myList.toJavaList();
  • //Semaphore is defined in java.util.concurrent

Semaphore p = ...; //Megaphore is not defined in java.util.concurrent //so it must be in the same package as MyClass Megaphore m = ...; } }

Import example

slide-23
SLIDE 23

Slide

The Java Type System

  • Who guarantees that a method is found in an
  • bject’s class or super classes?
  • In many languages: nobody (i.e., testing)
  • In Java: the Java Type System
  • a static analysis done by the compiler at compile-

time

  • For this to work, there are some requirements on

what a programmer can/must do

23

slide-24
SLIDE 24

Slide

Types

  • In Java, each class and interface defines a type
  • “Type” is here just a name for saying that the

compiler knows about the method tables, fields, and inheritance hierarchy

  • The Java type system is modular:
  • It only looks at one class/method at a time and

uses only information it can get from there

  • ⇒ Don’t be too smart, because the type system

isn’t that smart either!

24

slide-25
SLIDE 25

Slide

Static vs. Runtime Type

25

public int sumBalance(BankAccount one, BankAccount other) { int balanceOne = one.getBalance(); int balanceOther = other.getBalance(); return balanceOne + balanceOther; }

  • What is the type of ‘one’?
  • BankAccount
slide-26
SLIDE 26

Slide

Static vs. Runtime Type

26

public int sumBalance(BankAccount one, BankAccount other) { /*...*/ }

  • What is the type of ‘one’ now? PrivatePersonAccount?
  • Yes, at runtime; but the compiler just takes “BankAccount”
  • What is the type of ‘ppa’?
  • PrivatePersonAccount
  • What is the type of ‘bca’?
  • BankAccount (yes, the compiler forgets THAT fast!)

public void main(String [] args) { PrivatePersonAccount ppa = new PrivatePersonAccount(); BankAccount bca = new BusinessCustomerAccount(); system.out.println(sumBalance(ppa, bca)); }

slide-27
SLIDE 27

Slide

When Static and Runtime Types Collide

  • As long as Java’s type system works: perfect
  • But sometimes, the static and dynamic worlds collide
  • If the compiler cannot verify something, you as the

programmer have to insert checks that are performed at runtime

  • downcasts
  • instanceof
  • Runtime checks either succeed or throw an

exception

27

slide-28
SLIDE 28

Slide

if (other instanceof BankAccount) { } else { return false; //or super.equals(other); } }

instanceof and Cast Example

28

public class BankAccount { /* ... */ public boolean equals(Object other) { } } public class SomeClass { public void compareAccounts(BankAccount otherAccount) { BankAccount myAccount = ...; if (myAccount.equals(otherAccount)) { /*...*/ } } }

Implicit Upcast: BankAccount→Object Runtime type check Implicit Downcast: Object→BankAccount

BankAccount otherAccount = (BankAccount)other; return this.balance == otherAccount.balance;

slide-29
SLIDE 29

Slide

Four Random Leftovers

  • Constructors: Special methods that initialize a new
  • bject; including overloading and super-calls
  • Exceptions: exceptional control flow with throw and

try-catch-finally

  • Subtyping: An object of a subtype must work in all

places where an object of one of its supertypes is expected (think about what this means for the method tables, overriding, and overloading!)

  • Static:

You can also define fields and methods for a class itself, not only for object instances.

29

slide-30
SLIDE 30

Questions?