oop in java and c++ cs 123/cs 231. outline zprogram structure and execution zencapsulation and...

36
OOP in Java and C++ CS 123/CS 231

Upload: hugh-beasley

Post on 26-Dec-2015

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

OOP in Java and C++

CS 123/CS 231

Page 2: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Outline

Program Structure and ExecutionEncapsulation and InheritanceObjects, Variables, and ArraysConstructorsMethods, Operators, and BindingContainers and ReuseGUI Programming

Page 3: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Program Structure

Class definition similar in Java and C++Java: two types of programs

application (with main() function)applet (typically embedded in a web page)

C++a program is (still) a collection of functions

that may use objects and classesmain() function serves as driver

Page 4: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Program Execution

Java: Virtual Machine (VM)programs: both compiled and

interpretedcompiler produces .class from .javaVM loads .class file(s) as needed

C++: compiled, linked, and loadedmodules separately compiledlinked to produce executablestatic vs dynamic libraries

Page 5: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Encapsulation

Enforced through access keywordspublic: for interfaceprivate: to make implementation

inaccessibleprotected: access for subclasses only

In Javaeach member is prefixed with a keyword

In C++public, private, and protected sections

Page 6: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Breaking Encapsulation

Possible in C++ through the friend keyword

A method or class may be declared as a friend of an existing class

Allows access to private members

“A friend is someone who has access to your private parts.”

Page 7: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Inheritance

Feature that allows a class to be defined based on another classmethods and attributes are inherited

Java and C++ difference Java: public class A extends B { … }C++: class A: public B { … }

(different types of inheritance)

Multiple inheritance possible in C++, not in JavaBut in Java, one may implement several interfaces

Page 8: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Objects and Identity

Questions:How/when are objects created?What is the relationship between a

variable and an object?Difference between Java and C++

distinction between primitive (built-in) type variables and variables for objects

reference relationship between variable and actual object

Page 9: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Variables for Built-in Types

Variables for built-in types (C++ and Java)

int x; …x = 5; 5

X

X

Page 10: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Reference Variables(in Java)

Reference type variables

Button x; …x = new Button(“click”);

X

X

“click”

Button Object

Page 11: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Variables That “hold” Objects (in C++)

Declaration of an object variable allocates space for the object

Button x(“Click”);

“click”

X

Page 12: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Pointers (in C++)

Variables can be explicitly declared as pointers to objects

Button *x; …x = new Button(“click”);

X

X

“click”

Button Object

Page 13: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Disposing ofAllocated Memory

In Java, garbage collection is automaticMemory allocated objects are reclaimed

when no variables refer to themNeed to set reference variables to null

when the object is no longer neededIn C++, object destruction is the

programmers responsibility using the delete keyword

Page 14: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

delete in C++

There should be a delete for every newSomeClass *x = new SomeClass(…);// … use object pointed to by xdelete x; // done using object

Memory leakOccurs when you forget to deleteWasted memoryCan this occur in Java?

Page 15: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Object Construction

Constructorplace where you include code that

initializes the objectDefault Constructor

no additional info requiredUser-defined Constructor

with parameters that specify values or sizes

Page 16: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Arrays

int x[20]; Button b[20];Valid declarations in C++, not in JavaCreates 20 ints and 20 Button objects

In Java,Declaration and array creation separateFor object arrays, individual object

creation necessary

Page 17: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Pointers and Arrays

In C++, there is a close relationship between pointers and arrays

Instead of int x[20]; can issueint *x; x = new int[20];to allow for dynamic allocationUsage of the array (e.g., x[3] = 5;)

identical in both casesTo deallocate, use delete [] x;

Page 18: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Constructors in Java and C++

In Java,a constructor is invoked only through

the new keywordrecall that all object variables are

referencesIn C++,

a constructor is called upon variable declaration, or explicitly through new with pointers, or in other situations

other types of constructors

Page 19: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

C++ Destructor

Special method whose signature is a ~ followed by the name of the classe.g., ~SomeClass();

Particularly if the class contains pointers and the constructor contains calls to new, a destructor needs to be definede.g., SomeClass() { A = new int[20]; }

~SomeClass() { delete [] A; }

Page 20: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

C++ Control Over Copy and AssignmentIn C++, the semantics of “a = b”

(assignment) can be specifiedby defining the copy-assignment

operatorIn C++, there is a copy constructor

specifies what happens during object copying, e.g., when function parameters are passed

There is more low-level controlshallow copy vs deep copy

Page 21: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Methods

Defines object behaviorStatic methods vs instance methodsMethod overloading

within class, two methods with the same name but different signatures

Method overridingsame signatures across different classes

(subclass and superclass)

Page 22: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Operators

In C++, operators like =, +, *, ==, etc. can be defined, just like methods

Example:class Matrix {

// ... Matrix operator+(Matrix m) { … } // …}

c = a + b; // equiv to c = a.operator+(b);

Page 23: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Method Binding

Let Teacher be a subclass of EmployeeAlso, suppose promote() is a method defined

in both classesEmployee variables can refer to Teachers

In Java, Employee e; … e = new Teacher();In C++, Employee *e; … e = new Teacher;

e.promote() (or (*e).promote() ) calls which promote() method?

Page 24: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Static vs Dynamic Binding

In C++, Employee’s promote() is calledDetermined at compile time and deduced

from the type of the variable (static binding)

In Java, Teacher’s promote is calledDetermined at run-time because the actual

type of the referred object is checked then (dynamic binding)

* C++ uses virtual functions for dynamic binding

Page 25: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Static Binding

Pointer is typed to know the base class and is ignorant of the structure or existence of the derived classes

If the virtual keyword is NOT used, if a derived class has its own variation on the implementation of a base class member function, it will NOT cause the derived class version to be selected when a function is invoked on an object of than class through a variable declared in terms of the base class.

Page 26: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Another example

class Employee{public: double salary() {return sal;} double computeRaise() {return 25;} Employee(double salary) {sal = salary;}private: double sal;};

class Manager: public Employee

{public: double computeRaise() {return 100;} Manager(double

Salary) : Employee (salary)

{}};

Page 27: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Sample continued

Driver Code:Manager * boss1 = new Manager(2000);double boss1Salary = boss1->salary(); // 2000Employee *boss2 = new Manager(2300);double *boss2Salary = boss2->salary(); //2300double boss1Raise = boss1->computeRaise(); //

100double boss2Raise = boss2->computeRaise(); //

25

Page 28: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

C++ Run Time Binding

If the intent is for the selection of the function to be determined by the object’s class, not by the declaration of the pointer used to address it:Declare some base class members to be

virtualIf virtual, the compiler will deposit the

“type field” of the class in the object

Page 29: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Virtual Functions

Base class usually defines a body for a virtual function.

Inherited by derived class as default if it chooses not to override the implementation

Virtual keyword in function declaration, not in definition

Page 30: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Containers

Examples: Lists, Stacks, Files, etc.Structures that “contain” elementsOften, the element’s type has little

or nothing to do with the containers’ operations

Possible room for re-useunified container code for a stack of

integers, a stack of webpages, a stack of strings, ...

Page 31: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Java and the Object Hierarchy

All classes extend the Object class:A variable of class Object can refer to

any Java objectExample:

public class Stack { Object A[]; int top; // … void push(Object elt) // ...}

Page 32: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

C++ and Templates

Templates allow for a generic definitionparameterized definition, where the

element type is the parameterExample:

template<class T>class Stack<T> { T A[MAX]; int top; public: void push(T element) // …}

Page 33: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

C++ Templates

<class T> indicates that a template is being declared

T is the type name (can be a class)Usage example:

Stack <int> iStack;Stack <Cards> cStack;

where Cards is a user defined class

A type used as a template argument must provide the interface expected by the template

Page 34: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

Defining a Template

When defining a template member outside of its class, it must be explicitly declared a template

Exampletemplate <class T> Stack<T>::Stack()

Page 35: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

C++ Standard Containers

Vector : 1-D array of Tlist : double linked list of Tdequeue : double-ended queue of Tqueue : queue of Tstack : stack of Tmap : associative array of Tset : set of Tbitset : set of booleans

Page 36: OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors

GUI Programming

In Java, GUI is part of its development kitjava.awt.* is a collection of classes that

support visual programming and graphicsvisual objects (buttons, text fields, etc),

layout managers, events, etc.In C++

not part of the languagelibraries dependent on platform (e.g., MFCs

and Motif)