44
CS216 / SE211 1 Chapter 04 Introduction to Classes and Objects

CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

Embed Size (px)

Citation preview

Page 1: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 1

Chapter 04

Introduction to

Classes and Objects

Page 2: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 2

Objectives

• To study a history of OO concepts

• To understand concepts of OOP.

– Objects

– Classes

Each discussion focuses on how these concepts relate to the real world.

• To understand the differences between primitive variables and

reference variables.

• To study how to use variables as arguments and as return types.

• To learn how to refer or invoke object’s fields and methods.

Page 3: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 3

A Bit of OOP History

• 1960s : Simula 67 was firstly introduced.• Simula 67 is a programming language designed for making

simulations.• It has been created by Ole-John Dahl and Kristen Nygaard of the

Norwegian Computing Center in Oslo.

• Reportedly, the story is that they were working on ship simulations, and were confounded by the combinatorial explosion of how the different attributes from different ships could affect one another. The idea occurred to group the different types of ships into different classes of objects, each class of objects being responsible for defining its own data and behavior.

Page 4: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 4

A Bit of OOP History

Ole-John Dahl Kristen Nygaard

Page 5: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 5

A Bit of OOP History

• 1970s: Smalltalk • The Smalltalk language was developed at Xer

ox PARC introduced the term Object-oriented programming to represent the pervasive use of objects and messages as the basis for computation

• Object-oriented programming developed as the dominant programming methodology during the mid-1990s and until now.

Page 6: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 6

Time Line of Computer Languages

• 1957 Fortran by John Backus (IBM): Still favorite language of physicists. • 1959 Lisp (LISt Processing) introduced by McCarthy: First to use recursion, first-

class functions, garbage collection. Intended for AI. • 1960 Cobol (Common Business Oriented Language). • 1960 Algol (ALGOrithmic Language): Block structure, data types, BNF notation. • 1964 Basic by Kemeny and Kurtz. • 1967 Simula: Introduced classes, coroutines, instancing (data abstraction). • 1971 Pascal from Niklaus Wirth: Intended as stepping-stone to learn Algo and

Fortran. • 1972 C from Dennis Ritchie: Born out of Pascal, B and BCPL. Built for Unix, fast

and low-level. • 1972 Prolog: Logic, rule-based language (predicate calculus), used in AI. • 1975 Scheme by Guy Steele and Gerald Sussman: simplified Lisp. • 1979 Common LISP Object System • 1980 (1970 to 1983) Smalltalk by Alan Kay: Pure OO language (partly based on

Simula).

Page 7: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 7

Time Line of Computer Languages

• 1983 Objective C • 1984 Ada commissioned by the U.S. Department of Defence: For real-time syste

ms, e.g., used for controlers in air-planes. • 1986 (1991 release 3.0) C++ started by Bjarne Stroustroup: Speed of C with OO

features, includes templates and multiple inheritance. • 1987 Actor, Eiffel by Bertrand Meyer: Intended to be OO and multi-platform. Ba

sed on ideas of C++. • 1987 Perl by Larry Wall: Scripting Language, combines C, awk, sed, sh, and BA

SIC. • 1991 Python by Van Rossum. • 1995 PHP (PHP Hypertext Preprocessor) by Rasmus Lerdorf. • 1995 Ruby by Yukihiro Matsumoto: High-level OO scripting languages. • 1995 Lingo by John Thompson: Scripting language for Windows, used by Direct

or. Written for non-programmers.• 1996 Java by James Gosling (at SUN Micro Systems): Uses a virtual machine,

almost all features of C++. • 2001 (2004 version 2.0) ActionScript by Macromedia: Introduced with Flash,

reminds of JavaScript.

Page 8: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 8

Java Version History• The Java project has seen many release versions. Since 1997 they are:• J2SE 1.1.4 (Sparkler) September 12, 1997

– JDK 1.1.5 (Pumpkin) December 3, 1997 – JDK 1.1.6 (Abigail) April 24, 1998 – JDK 1.1.7 (Brutus) September 28, 1998 – JDK 1.1.8 (Chelsea) April 8, 1999

• J2SE 1.2 (Playground) December 4, 1998 – J2SE 1.2.1 (none) March 30, 1999 – J2SE 1.2.2 (Cricket) July 8, 1999

• J2SE 1.3 (Kestrel) May 8, 2000 – J2SE 1.3.1 (Ladybird) May 17, 2001

• J2SE 1.4.0 (Merlin) February 13, 2002 – J2SE 1.4.1 (Hopper) September 16, 2002 – J2SE 1.4.2 (Mantis) June 26, 2003

• J2SE 5.0 (1.5.0) (Tiger) September 29, 2004 • Java SE 6 (1.6.0) (Mustang) December 11, 2006 [5] • Java SE 7 (1.7.0) (Dolphin) anticipated for 2008

Page 9: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 9

For more information…

• http://en.wikipedia.org/wiki/Object-oriented_programming• http://www.felixgers.de/teaching/oop/oop_history.html• http://www.java.com/en/javahistory/• http://en.wikipedia.org/wiki/Java_(programming_language)

Page 10: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 10

OOP Concepts

Page 11: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 11

What is an Object?

• Object can be anything in real world.

• For example, Pan and James, desk, television, bicycle, etc.

• Real-world objects share two characteristics:– State– behavior

Page 12: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 12

Real World Object Examples

• Pan– State

• Name• Height• Weight• Blood group• Breed• Age

– Behavior• Walking• Thinking• Standing• Sitting• Running• Jumping

• James– State

• Name• Height• Weight• Breed• Color• Age

– Behavior• Walking• Sitting• Running• Sleeping• Barking• Wagging tail

Page 13: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 13

Real World Object Examples

• Television– State

• Brand name• Model• Size• Color mode• On-off state• Level of color• Level of volume

– Behavior• Tuning on-off• Color adjusting• Volume controlling• Channel changing

• Bicycle– State

• Current gear• Current speed• Brand name• Size

– Behavior• Changing gear• Applying brakes.

Page 14: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 14

Clues to Understand OOP.

“Identifying the state and behavior for real-world objects is a great way to

begin thinking in terms of

object-oriented programming.”

Page 15: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 15

Quiz!

• Take a minute to observe the real-world objects that are in your immediate area.

• For each object, answer these two questions:– What possible states can this object be in?– What possible behavior can this object

perform?

Page 16: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 16

Software Objects

• Software Objects are conceptually similar to real-world objects:– They consist of state and related behavior.– States can be stores as fields (attributes, variables)– Behavior can be exposed through methods

(functions)

• Each object is independent to each other.

Page 17: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 17

Benefits of Bundling code into individual software objects

• Modularity: The source code for an object can be written and maintained independently of the source code for other objects.

• Information-hiding: The details of its internal implementation remain hidden from the outside world.

• Code re-use.• Pluggability and debugging ease.

Page 18: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 18

What is a Class?

• In the real world, many individual objects are all of the same kind.

• A class is the blueprint from which individual objects are created.

Page 19: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 19

A Bicycle Class

class Bicycle {int speed = 0;int gear = 1;void speedUp (int increment) {

speed = speed + increment;}void applyBrakes (int decrement) {

speed = speed - decrement;}void changeGear (int newValue) {

gear = newValue;}void printStates() {

System.out.println("speed: "+speed+" gear: "+gear);}

}

Class Bicycle

Fieldsspeed: intgear: int

Methodsvoid speedUP (int)void applyBrakes (int)void changeGear (int)void printStates()

Page 20: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 20

Bicycle Democlass BicycleDemo {

public static void main(String args[]) {Bicycle bike1 = new Bicycle();Bicycle bike2 = new Bicycle();

bike1.speedUp(10);bike1.changeGear(2);bike1.printStates();

bike2.speedUp(15);bike2.changeGear(2);bike2.speedUp(10);bike2.printStates();

bike2.applyBrakes(20);bike2.changeGear(1);bike2.printStates();

}}

speed: 10 gear: 2speed: 25 gear: 2speed: 5 gear: 1

Page 21: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 21

Examples (structured programming VS OOP)

• โปรแกรมจำ�ลองกรแสดงระด�บน้ำ��ม�น้ำใน้ำรถยน้ำต์� 2 คั�น้ำ โดยที่��– คั�น้ำแรก ม�น้ำ��ม�น้ำอย��ใน้ำถ�ง 60%– คั�น้ำที่��สอง ม�น้ำ��ม�น้ำอย�� 20%

• รถยน้ำต์�คั�น้ำแรกแวะเต์"มน้ำ��ม�น้ำไป 40%• ส�วน้ำรถยน้ำต์�คั�น้ำที่��สอง ใช้%น้ำ��ม�น้ำจำน้ำหมดถ�ง• จำงเขี�ยน้ำโปรแกรมเพื่)�อแสดงระด�บน้ำ��ม�น้ำขีองรถแต์�ละ

คั�น้ำ

Page 22: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 22

Examples (structured programming VS OOP)

Solution I{ written by using Turbo Pascal in structured programming style }Program fuel_level;Var level : real;Begin

level := 60.0;level := level + 40.0;writeln(‘The fuel left in the first car is ‘,

level);level := 20.0;level := level – 20.0;writeln(‘The fuel left in the second car is ‘,

level);End.

Page 23: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 23

Examples (structured programming VS OOP)

Solution II{ written by using Turbo Pascal in structured programming style }Program fuel_level_II;

Procedure first_car();Var level : real;Begin

level := 60.0;level := level + 40.0;writeln(‘The fuel left in the first car is ‘, level);

End;Procedure second_car();Var level : real;Begin

level := 20.0;level := level – 20.0;writeln(‘The fuel left in the second car is ‘, level);

End;Begin

first_car();second_car();

End.

Page 24: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 24

Examples (structured programming VS OOP)

Class Fuel_level

Fields- f_level: double

Methods+void fill (double)+void used (double)+double getLevel ()

Page 25: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 25

Solution III// written by using Java

public class Fuel_level {private double f_level = 0.0;

public void fill (double amt) { f_level += amt; }public void used (double amt) { f_level -= amt; }public double get_level () { return f_level; }

public static void main (String args[]) {Fuel_level car1 = new Fuel_level (60);Fuel_level car2 = new Fuel_level (20);car1.fill (40);car2.used (20);System.out.println(car1.get_level());System.out.println(car2.get_level());

}

}

Examples (structured programming VS OOP)

Page 26: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 26

Classes VS Objects

• A class is not an object.• It’s used to construct them.• A class is a blueprint for an object.• It tells the virtual machine how to make an

object of that particular type.• Each object made from that class can have

its own values for the instance variables of that class.

Page 27: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 27

Making Your First Object

• Let’s create a Dog class by following these steps.– Design states/fields and methods for

dogs.– Write the Dog class.– Write a tester class to test the Dog class.

Page 28: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

Primitives and References

CS216 / SE211 28

Page 29: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 29

Primitive VS Reference

• Variables come in two flavours:-– Primitive– Reference

• Another view of variables is:-– Local variables – variables declared within a

method.– Instance variables – variables declared as an

object.

Page 30: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 30

QuizFrom the following Java code, classify variables of the code in two groups, instance variables and local variables.

class Dog {String name;int age;void setName(String name) {

this.name = name;}void setAge(int age) {

this.age = age;}void showInfo() {

System.out.println("Dog's name: " + name);System.out.println("Age : " + age + "years");

}} // end of class Dog

class TestDog {public static void main(String arg[]) {

Dog d1 = new Dog();d1.setName("Nick");d1.setAge(3);d1.showInfo();

}} // end of class TestDog

Page 31: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 31

Variables Characteristics

Variables must have a type

Variables must have a name

Example:-int countInt;Rabbit charlie;

Page 32: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 32

Primitive Variables

• Primitives hold fundamental values:-– boolean and char

• boolean (JVM-specific) true or false• char 16 bits 0 to 65535

– Numeric (all are signed)• integer

– byte 8 bits -128 to 127– short 16 bits -32768 to 32767– int 32 bits -2147483648 to 2147483647– long 64 bits -huge to huge

• floating point– float 32 bits varies– double 64 bits varies

• Be careful: You can’t put a large value into a small cup.

Page 33: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 33

Quiz• From the following list, choose the statements that would be legal

if these lines were in a single method:1. int x = 34.5;2. boolean boo = x;3. int g = 17;4. int y = g;5. y = y + 10;6. short s;7. s = y;8. byte b = 3;9. byte v = b;10. short n = 12;11. v = n;12. byte k = 128;

Page 34: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 34

Object Reference Variables

• An object reference variable holds bits that represent a way to access an object.

• It doesn’t hold the object itself, but it holds something like a pointer. Or an address.

• Except, in Java we don’t know that whatever it is, it represents one and only one object.

• And the JVM knows how to use the reference to get to the object.

Page 35: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 35

Example: Class Circle

Circledouble radius = 5.0

findArea() : void

class Circle {/** The radius of this circle */double radius = 5.0

double findArea() {return radius * radius * Math.PI;

}}

Page 36: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 36

Creating Objects and Object Reference Variables

• Object declarationClassName objectReference;ex: Circle c;

• Object creationobjectReference = new ClassName();ex: c = new Circle();

• Object declaration and creation in one statement ClassName objectReference = new ClassName();

ex: Circle c = new Circle();

Page 37: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 37

The 3 Steps of Object Declaration,Creation and Assignment

Circle c = new Circle();

1 2

3

1. Declare a reference variable Circle c = new Circle();Tells the JVM to allocate space for a reference variable, and names that variable c. The reference variable is, forever, of type Circle.

2. Create an object Circle c = new Circle();Tells the JVM to allocate space for a new Circle object on the heap.

3. Link the object and the referenceCircle c = new Circle();

Assigns the new Circle to the reference variable c.

Page 38: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 38

Primitive Data Types VS Object References

Primitive typeint i = 1; 1i

Object type Circle c; nullc

new Circle();c: Circle

radius = 5.0

referencec

c =

Page 39: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 39

Primitive Data Types VS Object References

Primitive type assignment Object type assignment

i = j

before

1i

2j

after

2i

2j

c1 = c2

before

c1

c2

after

c1

c2

c1:Circle

radius = 5

c2:Circle

radius = 3

What is the value of c1.radius after the assignement?

Page 40: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 40

Accessing an Object’s Data and Methods

• References an object’s data

objectReference.data• Invokes an object’s method

objectReference.mothod(arguments)• Example

– myCircle.radius– myCircle.findArea()

Page 41: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 41

Declaring and Initializing Instance Variables

• Instance variables always get a default value.• If you do not explicitly assign a value to an

instance variable, or you do not call a setter method, the instance variable still have a value!!– integer 0– floating points 0.0– booleans false– references null

Page 42: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 42

Instance VS Local Variables

• Instance variables are declared inside a class but not within a method.

• Local variables are declared within a method.• Local variables must be initialized before use!

class Foo {public void go() {

int x;int z = x + 3;

}}

%javac Foo.javaFoo.java:4: variable x might not have been initialized

int z = x + 3; ^

1 error

Page 43: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 43

Java is so EASY

Page 44: CS216 / SE2111 Chapter 04 Introduction to Classes and Objects

CS216 / SE211 44

End of Chapter 04

Introduction to

Classes and Objects