510 likes | 758 Views
Introduction To OOP/Java and C++. CMSC 331 Shon Vick. Introduction . Data abstraction and OOP is a style or paradigm for system development Fundamental Notions data abstraction information hiding inheritance dynamic binding. Terminology. Class Instance Variables Class Variables
E N D
Introduction To OOP/Java and C++ CMSC 331 Shon Vick
Introduction • Data abstraction and OOP is a style or paradigm for system development • Fundamental Notions • data abstraction • information hiding • inheritance • dynamic binding
Terminology • Class • Instance Variables • Class Variables • Instance – • An object is an identified unit which has state and behavior • The state is stored in instance variables (sometimes called member variables) • Message • Method
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
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
Data and Methods/Interface Public Oper1 Oper2 DATA Oper4 Private Oper3
Messages and Methods Request Methods Message Response
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
Message Passing OOP • Message • Method • Mechanism depends on language • C++ • Virtual Table • Smalltalk • Method Table
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++
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
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
References • http://www.cs.umd.edu/~pugh/java/gettingStarted.html • http://www.gl.umbc.edu/~vick/331/lectures/Summer00/OOP/Intro_To_Java/
JAVAand C++ CMSC 331
Platform independence dibby.java doo.java shibby.java javac shibby.class doo.class dibby.class java
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.
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++ ?
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++
No pointers ? • 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 number of pointer-related errors
Automatic garbage collection • Objects are always allocated in the heap, using new, as in Foo f = new Foo(); • fitself is always allocated in the stack • the object referenced byfis 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
No multiple inheritance ? • 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 • 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
Functions are alwaysvirtual • All (non-static) functions in Java follow a late-binding process • 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
Other differences between Java & C++ • (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 • 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
Other cool stuff • 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
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. */
Some Similarities betweenC++ 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".
Some Differences betweenC++ and Java • Java has automatic garbage collection. C++ does not. • C++ has operator overloading. Java does not. • C++ says "function". Java says "method".
C++ and Java divide a program into pieces (for separate compilation) in different ways.
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.
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.
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.
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++.
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 dynamically.
Assignment (=) 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.
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
C++: a choice of parameter types.Java: no choice of parameter types. • C++: Call-by-value • void f(int n); • C++: Call-by-reference • void f(int& n); • Other C++ variants: • void f(const int& n); • void f(const int n);
C++: a choice of parameter types.Java: no choice of parameter types. • Java all parameters are call-by-value. • But, it is almost like there are different parameter types for primitive types and classes.
Java: no choice of parameter 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-by-reference. public void f(String n) {...}
C++: a choice of parameter types.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.
C++: a choice of parameter types.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.
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.
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.
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? • int n = computeNewValue(); • OR use class objects.
public class Stuff { private int n; .... public void changeTheN(Stuff s) { s.n = 42; } }
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
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");
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) {…} outputStream.println("To file");
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
UMBC Wrap Up Questions?
Advanced Features • For a good discussion of the features added in Java 1,5 see http://www.cs.umd.edu/class/spring2005/cmsc132/lecs/lec35.pdf