oop in java by kasper b. graversen1 oop in java /ebuss kasper b. graversen lecture 2

48
OOP in Java by Kasper B. Graversen 1 OOP in Java /EBUSS OOP in Java /EBUSS Kasper B. Graversen Lecture 2

Post on 19-Dec-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

OOP in Java by Kasper B. Graversen 1

OOP in Java /EBUSSOOP in Java /EBUSS

Kasper B. GraversenLecture 2

OOP in Java by Kasper B. Graversen 2

Course changeCourse change• Due to lack of computers

– Labs from 9-12 in 3.15 + 3.16 – Lectures 13-16 in 3.14– 7 out of 9 homework assignments must be

passed– First one will be given next Wednesday

• Today stops at 12• Course homepage

http://www.it-c.dk/~kbilsted

OOP in Java by Kasper B. Graversen 3

Questions/commentsQuestions/comments

• Did the book make any sense?• Do you have a question for today’s

chapter?

OOP in Java by Kasper B. Graversen 4

On the right trackOn the right track• Code-Compile-Execute

cycle• Installed and played with

the compiler

•Smallest Java programclass A{ public static void main(String[] args) { System.out.println(“java is fun”); }}

OOP in Java by Kasper B. Graversen 5

On the right track 2On the right track 2• Stay on the right side of the

tracks. • Use the compiler and play with

the examples the book presents

• Flunking-% on this type of course at IT-C is ~40%

OOP in Java by Kasper B. Graversen 6

Course dictionaryCourse dictionary• Attribute,variable:Attribute,variable:

defines a property of an object• Method,function:Method,function:

defines functionality of an object• Class:Class:

Defines an object• Syntax:Syntax:

What we write• Semantics:Semantics:

The meaning of what we write

OOP in Java by Kasper B. Graversen 7

Today’s programToday’s program

• Documentation 101• Simple types• Objects• Coding style

OOP in Java by Kasper B. Graversen 8

Comments 101Comments 101• // till end of the line• /* spanning multiple lines */

• /** special comments spanning multiple lines */

• Comments always above or to the right of what is being commented on!

• Nesting is not allowed!

OOP in Java by Kasper B. Graversen 9

Today’s programToday’s program

• Documentation 101• Simple types• Objects• Coding style

OOP in Java by Kasper B. Graversen 10

The Java languageThe Java language

“In Java everything is an object!”

*

*Except for simple types

i.e. the car/shop

OOP in Java by Kasper B. Graversen 11

Simple types in JavaSimple types in Java

• Simple types are– boolean: boolean (logiske værdier)– integer: int long (heltal)– float: float double (kommatal)– character: char (a-Z-0-9)

• No ambiguity!– The current speed of a car is not just “a value”

its representation must be clearly expressed.

OOP in Java by Kasper B. Graversen 12

Simple types Simple types In earlier languages

• Simple types was all one had• It’s type was determined by its name

– i,j,k,l were integers a,b,c,d were chars

• In “BASIC” a variable could change type runtime

• In “C” these could be combined in structures - like a class with no functionality

OOP in Java by Kasper B. Graversen 13

Simple typesSimple types

• Why simple types?– Speed, storage space

• Why is a string not a simple type– Because it has functionality, ie.

String s = “hamburger”;System.out.print(s.substring(4,8));

gives “urge” not “burg”

OOP in Java by Kasper B. Graversen 14

How we count when How we count when programmingprogramming

• We always count from 0!– Seen in particularly old literature

• Thus the first position is in a string is position 0

• However, the length of a string is equal to the number of characters in the string, ie “foobar” == 6

OOP in Java by Kasper B. Graversen 15

How we represent How we represent characters in a computercharacters in a computer

• Each character is nothing but a integer value in the computer.

• These values are called ASCII values• In the computer world only the first 127

values are standardized. • Danish characters lies outside 127, thus it

can be problematic to transfer raw text from ie Windows to Mac

• Try holding down the alt key and type a number between 0-255 on the numeric pad and release all keys. (65 will produce an “A”)

OOP in Java by Kasper B. Graversen 16

How we represent simple How we represent simple types in a computertypes in a computer

• Is a predefined small chunk of the computers memory.

• These chunks are measured in “bits” and “bytes” - more on this in the next lecture.

OOP in Java by Kasper B. Graversen 17

How to use simple typesHow to use simple types

• Nothing new • We now know

how to specify these attributes and how we can represent them.

Wheel Wheel

WheelWheelMotor

Steering mechanism

Bodyspeed

colorprice cleanness

• Or maybe we are just confused on a higher level?

OOP in Java by Kasper B. Graversen 18

How would you represent How would you represent the attributes?the attributes?

class Motor{ int speed; // meter/hour}

What happens if I choose meter/second?

10 m/s = 36 km/h11 m/s = 39,6 km/hinsecurity of speed = 3,6 km/hfirst choice insecurity = 1 m/h

The motor

Motor

speed

OOP in Java by Kasper B. Graversen 19

How would you represent How would you represent the attributes?the attributes?

class Body{ int price; // in $ String color; // only “blue”, “black”, “green” ??? cleanness;}

How do we ensure only legal values are used? Is “bluegreen” a valid color and can the system handle it? Compare it? Etc.Sometimes the solution is to not use simple types.

The bodyBody

colorprice cleanness

OOP in Java by Kasper B. Graversen 20

Comments and attributesComments and attributes

• Still using comments to specify the units are important. A unit confusion between pounds and newtons led to NASA loosing $94 million on a Mars Climate Orbiter!

OOP in Java by Kasper B. Graversen 21

Today’s programToday’s program

• Documentation 101• Simple types• Objects• Coding style

OOP in Java by Kasper B. Graversen 22

The Java languageThe Java language

• Simple types• Classes• “Special classes”

– Integrated in the syntax• String• Array

– Always exists• System

OOP in Java by Kasper B. Graversen 23

Roles of objectsRoles of objects

• Data container– A king (name, birthyear, deathyear, sons etc.)

• Functionality provider– A dictionary, converters

• Mix– Bank account

• data: balance, name,...• functionality: deposit, withdraw, interest rate,...

– Human

OOP in Java by Kasper B. Graversen 24

Object theoryObject theory• An object is an encapsulation of

attributes and functionality.• Notably, it allows concealing of

internal representation and supplying easy to use methods.– speedup(int km) in a car. – deposit(int cent) in a bank account – match(Colour othercar)

• Allows creating a new kinds of types

OOP in Java by Kasper B. Graversen 25

Object TheoryObject Theory

Object

Internal representation

Objectinterfaces(aka methods)

OOP in Java by Kasper B. Graversen 26

Object TheoryObject Theory• Plato (428-348 BC) perceived the

world as flawed copies of ideas. All horses derive from the abstract idea “horse”

• This explained the different appearances of horses

OOP in Java by Kasper B. Graversen 27

Object TheoryObject Theory

• In Java a class is “the idea” • An object is “the copy”

– formally called an instantiation of the class.

• Designing classes is a matter of defining static structure.

OOP in Java by Kasper B. Graversen 28

Object TheoryObject Theory• How to model a horse?

class Horse{ String name; int energy; // limits 0-2

void walk() { if(energy > 0) energy--; } void appearance() { if(energy == 0) System.out.println(“dead”); if(energy == 1) System.out.println(“drowsy”); if(energy == 2) System.out.println(“fresh”); } void eat() { energy = 2; }}

OOP in Java by Kasper B. Graversen 29

Object TheoryObject Theory

• To create a horse, we must create an objectHorse h1 = new Horse();

• and set appropriate valuesh1.name = “lucas”;

h1.energy = 2;

• The dot-operator (.) gives access to the objects internals.

OOP in Java by Kasper B. Graversen 30

Object TheoryObject Theory

• FormallyHorse h1 = new Horse();

• isType nameOfPointer = new Type();

• h1 is of the type Horse• h1 has the ability to point to horse objects

• h1 is pointing at a freshly created object

OOP in Java by Kasper B. Graversen 31

Object TheoryObject TheoryHorse h1 = new Horse();h1.name=“silas”; h1.energy=2;

Horse h2 = new Horse();h2.name=“superhorse”; h2.energy=99;

h1

h2

Horse

Silas2

Horse

Superhorse99

OOP in Java by Kasper B. Graversen 32

Object TheoryObject Theoryint h3 = new Horse();h3.name=“jürgen”; h3.energy=2;

h1 < h2

h1

h2

Horse

Silas2

Horse

Superhorse99

h1.energy < h2.energy

h1 = h2

h1 == h2

OOP in Java by Kasper B. Graversen 33

Object TheoryObject Theory

Horse h1 = new Horse();Horse h2 = new Horse();

h1.name=“silas”; h2.name=“superhorse”;

h1.energy=2; h2.energy=99;

h1.appearance(); h2.appearance();

h1.walk(); h2.walk();

h1.appearance(); h2.appearance();

h1.walk(); h2.walk();

h1.appearance(); h2.appearance();

h1.walk(); h2.walk();

h1.appearance(); h2.appearance();

Poor Silas DIED due to a simple cheat!

...racing the horses...racing the horses

OOP in Java by Kasper B. Graversen 34

Object TheoryObject Theory

• The program was “mechanically” correct

• Unexpected input made it perform faulty

• Programming is more than working out the “mechanics” also the input/data needs be secured within expected limits.

……programs & inputprograms & input

OOP in Java by Kasper B. Graversen 35

Object TheoryObject Theory

• Setting up constraints in the comments clearly doesn’t suffice!

• Additionally its easy to forget to initialize all attributes

• Solution: add a constructor

……constructing valid objectsconstructing valid objects

Horse(String name, int e){ this.name = name; energy = e;}

Easy to type,hard to read!

No return type

OOP in Java by Kasper B. Graversen 36

Object TheoryObject Theory

• But constructors can also check input against the constraints of the class

……constructing valid objectsconstructing valid objects

Horse(String name, int energy){ this.name = name; if(energy < 3) this.energy = energy; else this.energy = 2;}

OOP in Java by Kasper B. Graversen 37

Object TheoryObject Theory• Constructors defines an interface

to creating objects• When the constructor is defined

Horse foo = new Horse(); is now illegal

• The new operator must obey the constructorHorse foo = new Horse(“max”, 2);

A string An integer

OOP in Java by Kasper B. Graversen 38

Starting programsStarting programs• How do we get

started?– Functionality resides

inside objects– And can only be

executed when objects are created

– It takes functionality to create objects

Horse h1 = new Horse(“silas”,2); Horse h2 = new Horse(“super”,99);h1.appearance();h2.appearance();h1.walk(); h2.walk();h1.appearance();h2.appearance();h1.walk(); h2.walk();h1.appearance();h2.appearance();h1.walk(); h2.walk();h1.appearance();h2.appearance();

Our horse race

OOP in Java by Kasper B. Graversen 39

Starting programsStarting programs

• Java has a bootstrapping mechanism called main() which is automatically called when the virtual machine is started with a class.

• The static allows Java to access the main method before object creation.

OOP in Java by Kasper B. Graversen 40

Starting programsStarting programs

• javac *.java• java HorseRace

class HorseRace{ public static void main(String[] args) {

Horse h1 = new Horse(“silas”, 2);Horse h2 = new Horse(“superhorse”, 99);

h1.appearance(); h2.appearance();h1.walk(); h2.walk();h1.appearance(); h2.appearance();h1.walk(); h2.walk();h1.appearance(); h2.appearance();h1.walk(); h2.walk();h1.appearance(); h2.appearance();

}}

How do we get on from here?

OOP in Java by Kasper B. Graversen 41

Order of executionOrder of execution

• One line at a time• In order to use a variable/object it

must first be created

main(…){

beers = beers+1;int beers;

}

OOP in Java by Kasper B. Graversen 42

staticstatic is forbidden! is forbidden!

During compilation the compiler reports

class SomethingAbstract{ public static void main(String[] args) { f(); } void f() {…}}

A.java:5: non-static method f() cannot be referenced from a static context f(); ^

Must be read as: you forgot a new somewhere

static

OOP in Java by Kasper B. Graversen 43

Today’s programToday’s program

• Documentation 101• Simple types• Objects• Coding style

OOP in Java by Kasper B. Graversen 44

Code conventionsCode conventions

• Class names are always spelled with a starting capital letter

• The opposite for methods and attributes

• Attributes can not contain spaces so multiple words are concatenated– int theDogsMothersName

OOP in Java by Kasper B. Graversen 45

Code conventionsCode conventionsThe codes are identical to the compiler,are they to you too?

class A{public static void main(String[] args){f();}void f(){System.out.print("foo");}}

class A{ public static void main(String[] args) { f(); } void f() { System.out.print("foo");} }

OOP in Java by Kasper B. Graversen 46

Code conventionsCode conventionsclass A{ int a; String b;

A(String b, int a){…} void b(){…} void c(){…} void d(){…}}

class Horse{ String name; int energy; Horse(String name, int energy){…} void walk(){…} void appearance(){…} void eat(){…}}

Which do you prefer?

Spend time on proper naming.

OOP in Java by Kasper B. Graversen 47

Special classesSpecial classesAs String is a class not a simple type, writing

String s = “foo”;

means

String s = new String(“foo”);

Horse

Silas2

Should therefore be depicted as

Horse

name2

String

Silas

OOP in Java by Kasper B. Graversen 48

The endThe end