Introduction To OOP

advertisement
UMBC
Introduction To OOP/Java and C++
CMSC 331
Shon Vick
1
UMBC


Introduction
Data abstraction and OOP is a style
or paradigm for system development
Fundamental Notions
data abstraction
 information hiding
 inheritance
 dynamic binding

2
Terminology
UMBC

Class



Instance –




Instance Variables
Class Variables
An object is an identified unit which has state
and behavior
The state is stored in instance variables
(sometimes called member variables)
Message
Method
3
UMBC

Basic OOP Notions Java
Classes are the basic language
construct for creating programmer
defined data types that we'll use for
encoding ADTs - also provide
encapsulation through the use of
visibility keywords private, public, and
package
4
UMBC




Basic OOP Notions Java
Instance variables - describe the data in
abstract data types (each object instance
has its own copy of the data)
Class variables - describe the data in
abstract data types all object instances
share the value of the data (called static
fields in Java)
Messages request for an operation
Methods implementation of a request
5
Data and Methods/Interface
Public
Oper1
DATA
Oper2
Oper4
UMBC
Private
Oper3
6
Messages and Methods
UMBC
Request
Methods
Message
Message1
Args
Method1
Message1
Other Args
Method2
Message2
Args
Method3
Response
7
UMBC





What’s OOP
Everything is an Object
A program is a bunch of objects
communicating
Each object has its own memory made
up of other objects
Every Object has a type
All objects of a particular type can
receive the same messages
8
Message Passing OOP
UMBC


Message
Method
Mechanism depends on language
 C++



Virtual Table
Smalltalk

Method Table
9
UMBC



Support for OOP
Programming in Java
Derived classes - provide a mechanism for reuse
via inheritance. Data members as well as methods
of derived class are inherited from a base class
Java supports two constructs implements and
extends involving derivation
Inheritance of interface compared to inheritance
of implementation

Differences between Java and C++
10
UMBC



OOP Notions
Virtual methods - let a derived class
redefines methods from a base class
(overrides a method) and have the dispatch
happen at runtime - this is sometimes
called Dynamic binding (also called runtime
or late binding as opposed to compile time
or early binding) In Java/Smalltalk most binding is dynamic
In C++ you have options
11
UMBC


Contrast with
Imperative Programming
Function/Structs not Class/Methods
Fundamental Data Abstract
Mechanism
What’s lacking?
Objects do not behave like other types
 No encapsulation enforced
 Creation and Initialization are divorced

12
UMBC


References
http://www.cs.umd.edu/~pugh/java/g
ettingStarted.html
http://www.gl.umbc.edu/~vick/331/le
ctures/Summer00/OOP/Intro_To_J
ava/
13
UMBC
JAVA
and C++
CMSC 331
14
UMBC
Platform independence
shibby.java
dibby.java
doo.java
javac
shibby.class
dibby.class
doo.class
java
15
UMBC



Platform independence in Java
Wait… so does it mean that Java is an interpreted
language ? Yes, source is compiled into bytecodes.
Aren’t interpreted languages inherently slower than
compiled ones ? Yes.
Why you should not care so much, though:
 Java trades speed for


platform independence
safety (more on this later)
Java compilers are pretty darn good anyway
Still, if you’re really worried about speed, you may
always use the so-called just-in-time (JIT) compilers.


16
UMBC




Safe and easy to learn
The first thing to note here is that
these are relative terms
In this talk, we’ll compare Java and C++
The general consensus is that Java is
easier to learn and use than C++, but I’ll
let you be the judge of that.
Is Java safer than C++ ?
17
UMBC

Safer than C++ ?
What do we mean by “safe” anyway ?
Less prone to programmer mistakes

Java achieves better safety than C++ by






checking every array access for out-of-bounds errors
eliminating direct access to pointer operations
automatically reclaiming any (heap) memory space not in use
(automatic garbage collection)
having a less fragile approach to multiple inheritance
making every function virtual
providing, generally speaking, a simpler syntax than C++
18
No pointers ?
UMBC

Some people claim that Java has
no pointers… Not true!
 All
objects are accessed through
references, which are automatically
de-referenced pointers
 However, the pointer nature of
these references is hidden from
the programmer. Why ?
 Reduced
errors
number of pointer-related
19
UMBC

Automatic garbage collection
Objects are always allocated in the heap, using new, as in
Foo f
= new Foo();
itself is always allocated in the stack
 the object referenced by f is allocated in the heap
 recall that memory allocation in C++ is not so simple
Java keeps track of how many valid references exist for each
object – when an object has no more references to it, the
memory space it occupies in the heap gets reclaimed
No, it doesn’t mean that you may be sloppy
Automatic garbage collection has pros and cons
 Pro: prevents many common memory allocation bugs
 Con: has a negative impact on your program’s efficiency




f
20
UMBC

C++ inheritance forces the inheritance of both
data and behavior (code)


That’s a very fragile approach – in order to inherit some
behavior your class may have to gain some data as well,
even if it’s not really needed
Java solves that problem and at the same time
eliminates the need for multiple inheritance by
defining something called an interface



No multiple inheritance ?
Interfaces only define the expected behavior of a set of
functions, like a contract – no data and no implementation
A class may implement as many interfaces as needed
Of course, regular inheritance between classes is
still allowed, but a class may inherit from only one
other class - no multiple class inheritance in Java 21
UMBC

All (non-static) functions in Java follow a latebinding process




Functions are always virtual
Which function code is actually executed depends on the
actual run-time type of the object on which the function
is being called, not on the object’s declared type at
compile time
In C++, unless one declares a function to be
virtual, the code to be executed is decided at
compile time
Thus, in Java, all (non-static) functions are virtual
Late-binding is a little slower but prevents
common hard-to-find bugs
22
UMBC

(Almost) everything is an object







Only primitive types (boolean, char, int, long, float, double)
are not objects
Object is the common parent of evry Classes (except
Object)
Function arguments are always passed by value


Other differences between Java & C++
Objects are not copied – only their references are
Neat solution to name collisions (packages)
No separation between header and implementation
No operator overloading
No structs
No generics (templates) and no enums (constant
enumerations) until Java 2, 1.5
23
Other cool stuff
UMBC

Javadoc

Auto-documenting your code



Your comments are nicely formatted into a
set of HTML pages
C++ has something similar: Doxygen
Swing
Dynamically pluggable look-and-feel
(plaf)
 Powerful, easy-to-use GUI toolkit

24
UMBC
javadoc
Extracts an interface from a class
definition.
May not need full blown details for AP
course, but be consistent with
javadoc.
Comments before method headings:
/**
javadoc comment style.
25
*/
UMBC







Some Similarities between
C++ and Java
Simple (primitive) types: int, double, char
Control Structures if-else, switch, while,
for
Arithmetic expressions
Both have a string type:
C++ string,
Java String.
Arrays
Both have classes.
Both have a "main".
26
UMBC
Some Differences between
C++ and Java
 Java
has automatic garbage
collection. C++ does not.
 C++ has operator overloading.
Java does not.
 C++ says "function".
Java says "method".
27
UMBC
C++ and Java divide a program
into pieces (for separate
compilation) in different ways.
28
UMBC
C++: Traditionally has an
interface (header) file,
implementation file(s),
application (driver) file.
C++: Can confine a program to a
single file if you want.
29
UMBC
 Java:
A compilation unit is
always a class definition.
 Every public class is in a
separate file (except for
some special cases).
 No header files.
 Normally, you have no one file
programs in Java.
30
UMBC




More Subtle Differences
C++ has pointer types.
 Java has no pointer types .
Assignment (=) and equality comparison
(==) have minor differences.
C++ gives a choice of parameter types.
 Java: No choice of parameter types.
Exception handling can be avoided in C++
 Exception handling is needed for some
fundamental things in Java, e.g. file
I/O.
31
UMBC
Java has no pointer types
But Java does have "pointers".
 In Java class (and array) types
are REFERENCE TYPES.
 A reference is a "pointer". All
class values in Java are handled
as references, but it is all
automatic.
 In Java primitive types are just
like in C++.

32
UMBC



In Java a primitive type variable holds
values, just as in C++. int n = 42;
Java a class type variable contains a
reference ("pointer") to the object
(value).
However, this is all automatic. There are
no pointer types as such in Java.
PetRecord myDog =
new PetRecord("Fido", 3);
Note that all class objects are created
33
dynamically.
Assignment
UMBC
(=) and equality comparison
(==) have minor differences.
On primitive (simple) types, = and
== are the same in C++ and Java.
 In Java, = and == on classes (or
arrays) are comparing references
("pointers"),
 and you cannot overload
(redefine) = and == in Java.

34
UMBC




Assignment (=) and equality
comparison (==) have minor
differences.
If (n = 0) ….
In C++ this is probably an error with
no error message, assuming you meant
to use ==.
In Java this generates a compiler
error.
In Java ints neither are nor can they
be type cast to Booleans
35
C++:
a
choice
of
parameter
types.
UMBC
Java: no choice of parameter types.

C++: Call-by-value


C++: Call-by-reference


void f(int n);
void f(int& n);
Other C++ variants:
void f(const int& n);
 void f(const int n);

36
C++:
a
choice
of
parameter
types.
UMBC
Java: no choice of parameter types.
Java all parameters are call-byvalue.
 But, it is almost like there are
different parameter types for
primitive types and classes.

37
Java: no choice of parameter
UMBC
types,
but
 All primitive type
parameters are automatically
call-by-value.
public void f(int n)
{...}

All class types are automatically
something very much like call-byreference.
public void f(String n)
{...}
38
C++:
a
choice
of
parameter
types.
UMBC
Java: no choice of parameter types.
Java Full Story:
In Java primitive types are just like in
C++.
In Java class (and array) types are
REFERENCE TYPES.
A reference is a "pointer". All class values
in Java are handled as references, but it
is all automatic.





All parameters are call-by-value of a
reference.
39
C++:
a
choice
of
parameter
types.
UMBC
Java: no choice of parameter types.






Java Full Story:
In Java all parameters are call-by-value.
Parameter is a local variable initialized to
the value of the argument.
Primitive types no surprises.
Class type (local) variables hold
references.
Class parameters are call-by-value of a
reference.
40
UMBC
Java: no choice of parameter
types.
public void change(PetRecord r)
{
r.name = "FooFoo";
}
This really changes its PetRecord argument.
public void change(int n)
{
n = 42;
}
This does not change its int argument.
41
UMBC
Java: no choice of parameter
types.
public void change(int n)
{
n = 42;
}
This does not change its int argument.
There is no way to write a Java method that
has a parameter for an int variable and
that changes the value of an argument
variable.
42
There is no way to write a Java method
that has a parameter for an int variable
and that changes the value of an
argument variable.
So, how do you manage to cope?
UMBC

int n = computeNewValue();

OR use class objects.
43
UMBC
public class Stuff
{
private int n;
....
public void changeTheN(Stuff s)
{
s.n = 42;
}
}
44
UMBC



Exception handling
Can be avoided in C++
Exception handling is needed for some
fundamental things in Java, e.g. file I/O.
All exceptions inherent from Exception
45
UMBC
Exception handling in Java
Fake it with "magic formulas" approach:
public class TextFileOutputDemo
{
public static void main(String[] arg)
throws IOException
{
PrintWriter outputStream =
new PrintWriter(…));
outputStream.println("To file");
46
UMBC
public class TextFileOutputDemo
{ //without magic formula:
public static void main(String[] arg)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(
new FileOutputStream("out.txt"));
}
catch(FileNotFoundException e)
{…}
47
UMBC
Style Comparison C++/Java
Java uses loooong names:
e.g. FileNotFoundException
while C++ uses some abbreviations
Java spelling conventions:
ClassName, variableName, methodName,
LITERAL_NAME
Java has an official commenting style:
javadoc
48
UMBC
Questions?
Wrap Up
49
UMBC

Advanced Features
For a good discussion of the features
added in Java 1,5 see
http://www.cs.umd.edu/class/spring2
005/cmsc132/lecs/lec35.pdf
50
UMBC


References
http://wwwcse.ucsd.edu/users/savitch/APJava.p
pt
http://www.cs.ucr.edu/~titus/JavaFo
rC++
51
Download