Transcript class

Chapter 04
Introduction to
Classes and Objects
CS216 / SE211
1
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.
CS216 / SE211
2
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.
CS216 / SE211
3
A Bit of OOP History
Ole-John Dahl
CS216 / SE211
Kristen Nygaard
4
A Bit of OOP History
• 1970s: Smalltalk
• The Smalltalk language was developed at
Xerox PARC introduced the term Objectoriented 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 mid1990s and until now.
CS216 / SE211
5
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, firstclass 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).
CS216 / SE211
6
Time Line of Computer Languages
•
•
•
•
•
•
•
•
•
•
•
1983 Objective C
1984 Ada commissioned by the U.S. Department of Defence: For real-time
systems, 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.
Based on ideas of C++.
1987 Perl by Larry Wall: Scripting Language, combines C, awk, sed, sh, and
BASIC.
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
Director. 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.
CS216 / SE211
7
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.3 (Kestrel) May 8, 2000
•
J2SE 1.4.0 (Merlin) February 13, 2002
– J2SE 1.2.1 (none) March 30, 1999
– J2SE 1.2.2 (Cricket) July 8, 1999
– J2SE 1.3.1 (Ladybird) May 17, 2001
– 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
CS216 / SE211
8
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)
CS216 / SE211
9
OOP Concepts
CS216 / SE211
10
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
CS216 / SE211
11
Real World Object Examples
• James
• Pan
– State
•
•
•
•
•
•
Name
Height
Weight
Blood group
Breed
Age
– Behavior
•
•
•
•
•
•
Walking
Thinking
Standing
Sitting
Running
Jumping
CS216 / SE211
– State
•
•
•
•
•
•
Name
Height
Weight
Breed
Color
Age
– Behavior
•
•
•
•
•
•
Walking
Sitting
Running
Sleeping
Barking
Wagging tail
12
Real World Object Examples
• Television
– State
•
•
•
•
•
•
•
Brand name
Model
Size
Color mode
On-off state
Level of color
Level of volume
• Bicycle
– State
•
•
•
•
Current gear
Current speed
Brand name
Size
– Behavior
• Changing gear
• Applying brakes.
– Behavior
•
•
•
•
Tuning on-off
Color adjusting
Volume controlling
Channel changing
CS216 / SE211
13
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.”
CS216 / SE211
14
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?
CS216 / SE211
15
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.
CS216 / SE211
16
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.
CS216 / SE211
17
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.
CS216 / SE211
18
A Bicycle Class
Class Bicycle
class Bicycle {
Fields
int speed = 0;
speed: int
int gear = 1;
gear: int
void speedUp (int increment) {
speed = speed + increment;
Methods
}
void applyBrakes (int decrement) {
void speedUP (int)
speed = speed - decrement;
void applyBrakes (int)
}
void changeGear (int)
void changeGear (int newValue) {
void printStates()
gear = newValue;
}
void printStates() {
System.out.println("speed: "+speed+" gear: "+gear);
}
}
CS216 / SE211
19
Bicycle Demo
class 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: 2
speed: 25 gear: 2
speed: 5 gear: 1
}
}
CS216 / SE211
20
Examples (structured programming VS OOP)
• โปรแกรมจำลองกำรแสดงระดับน ้ำมันในรถยนต์ 2 คัน โดยที่
– คันแรก มีน ้ำมันอยูใ่ นถัง 60%
– คันที่สอง มีน ้ำมันอยู่ 20%
• รถยนต์คนั แรกแวะเติมน ้ำมันไป 40%
• ส่วนรถยนต์คนั ที่สอง ใช้ น ้ำมันจนหมดถัง
• จงเขียนโปรแกรมเพื่อแสดงระดับน ้ำมันของรถแต่ละคัน
CS216 / SE211
21
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.
CS216 / SE211
22
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.
CS216 / SE211
23
Examples (structured programming VS OOP)
Class Fuel_level
Fields
- f_level: double
Methods
+void fill (double)
+void used (double)
+double getLevel ()
CS216 / SE211
24
Examples (structured programming VS OOP)
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());
}
}
CS216 / SE211
25
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.
CS216 / SE211
26
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.
CS216 / SE211
27
Primitives and References
CS216 / SE211
28
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.
CS216 / SE211
29
Quiz
From 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
CS216 / SE211
class TestDog {
public static void main(String arg[]) {
Dog d1 = new Dog();
d1.setName("Nick");
d1.setAge(3);
d1.showInfo();
}
} // end of class TestDog
30
Variables Characteristics
Variables must have a type
Variables must have a name
Example:int countInt;
Rabbit charlie;
CS216 / SE211
31
Primitive Variables
• Primitives hold fundamental values:– boolean and char
• boolean
• char
(JVM-specific)
16 bits
true or false
0 to 65535
– Numeric (all are signed)
• integer
– byte
– short
– int
– long
8 bits
16 bits
32 bits
64 bits
-128 to 127
-32768 to 32767
-2147483648 to 2147483647
-huge to huge
32 bits
64 bits
varies
varies
• floating point
– float
– double
•
Be careful: You can’t put a large value into a small cup.
CS216 / SE211
32
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;
CS216 / SE211
33
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.
CS216 / SE211
34
Example: Class Circle
Circle
double radius = 5.0
findArea() : void
class Circle {
/** The radius of this circle */
double radius = 5.0
double findArea() {
return radius * radius * Math.PI;
}
}
CS216 / SE211
35
Creating Objects and
Object Reference Variables
•
Object declaration
ClassName objectReference;
ex: Circle c;
•
Object creation
objectReference = new ClassName();
ex: c = new Circle();
•
Object declaration and creation in one statement
ClassName objectReference = new ClassName();
ex:
CS216 / SE211
Circle c = new Circle();
36
The 3 Steps of Object Declaration,
Creation and Assignment
3
Circle
c
=
new Circle();
1
2
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 reference
Circle c = new Circle();
Assigns
CS216
/ SE211
the new Circle to the reference variable c.
37
Primitive Data Types VS Object References
Primitive type int
Object type
i = 1;
Circle c;
c = new Circle();
i
1
c
null
reference
c: Circle
radius = 5.0
CS216 / SE211
38
Primitive Data Types VS Object References
Primitive type assignment
Object type assignment
i = j
c1 = c2
before
i
1
i
2
j
2
j
2
CS216 / SE211
before
after
after
c1
c1
c2
c2
c1:Circle
c2:Circle
radius = 5
radius = 3
What is the value of c1.radius after the assignement?
39
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()
CS216 / SE211
40
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
floating points
booleans
references
CS216 / SE211
0
0.0
false
null
41
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;
}
}
CS216 / SE211
%javac Foo.java
Foo.java:4: variable x
might not have been
initialized
int z = x + 3;
^
1 error
42
Java is so EASY
CS216 / SE211
43
End of Chapter 04
Introduction to
Classes and Objects
CS216 / SE211
44