Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors."— Presentation transcript:

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

2 Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors zMethods, Operators, and Binding zContainers and Reuse zGUI Programming

3 Program Structure zClass definition similar in Java and C++ zJava: two types of programs Õapplication (with main() function) Õapplet (typically embedded in a web page) zC++ Õa program is (still) a collection of functions that may use objects and classes Õmain() function serves as driver

4 Program Execution zJava: Virtual Machine (VM) Õprograms: both compiled and interpreted Õcompiler produces.class from.java ÕVM loads.class file(s) as needed zC++: compiled, linked, and loaded Õmodules separately compiled Õlinked to produce executable Õstatic vs dynamic libraries

5 Encapsulation zEnforced through access keywords Õpublic: for interface Õprivate: to make implementation inaccessible Õprotected: access for subclasses only zIn Java Õeach member is prefixed with a keyword zIn C++ Õpublic, private, and protected sections

6 Breaking Encapsulation zPossible in C++ through the friend keyword zA method or class may be declared as a friend of an existing class zAllows access to private members “A friend is someone who has access to your private parts.”

7 Inheritance zFeature that allows a class to be defined based on another class Õmethods and attributes are inherited zJava and C++ difference ÕJava: public class A extends B { … } ÕC++: class A: public B { … } (different types of inheritance) zMultiple inheritance possible in C++, not in Java ÕBut in Java, one may implement several interfaces

8 Objects and Identity zQuestions: ÕHow/when are objects created? ÕWhat is the relationship between a variable and an object? zDifference between Java and C++ Õdistinction between primitive (built-in) type variables and variables for objects Õreference relationship between variable and actual object

9 Variables for Built-in Types zVariables for built-in types (C++ and Java) int x; … x = 5; 5 X X

10 Reference Variables (in Java) zReference type variables Button x; … x = new Button(“click”); X X “click” Button Object

11 Variables That “hold” Objects (in C++) zDeclaration of an object variable allocates space for the object Button x(“Click”); “click” X

12 Pointers (in C++) zVariables can be explicitly declared as pointers to objects Button *x; … x = new Button(“click”); X X “click” Button Object

13 Disposing of Allocated Memory zIn Java, garbage collection is automatic ÕMemory allocated objects are reclaimed when no variables refer to them ÕNeed to set reference variables to null when the object is no longer needed zIn C++, object destruction is the programmers responsibility using the delete keyword

14 delete in C++ zThere should be a delete for every new ÕSomeClass *x = new SomeClass(…); Õ// … use object pointed to by x Õdelete x; // done using object zMemory leak ÕOccurs when you forget to delete ÕWasted memory ÕCan this occur in Java?

15 Object Construction zConstructor Õplace where you include code that initializes the object zDefault Constructor Õno additional info required zUser-defined Constructor Õwith parameters that specify values or sizes

16 Arrays zint x[20]; Button b[20]; ÕValid declarations in C++, not in Java ÕCreates 20 ints and 20 Button objects zIn Java, ÕDeclaration and array creation separate ÕFor object arrays, individual object creation necessary

17 Pointers and Arrays zIn C++, there is a close relationship between pointers and arrays zInstead of int x[20]; can issue int *x; x = new int[20]; to allow for dynamic allocation ÕUsage of the array (e.g., x[3] = 5;) identical in both cases ÕTo deallocate, use delete [] x;

18 Constructors in Java and C++ zIn Java, Õa constructor is invoked only through the new keyword Õrecall that all object variables are references zIn C++, Õa constructor is called upon variable declaration, or explicitly through new with pointers, or in other situations Õother types of constructors

19 C++ Destructor zSpecial method whose signature is a ~ followed by the name of the class Õe.g., ~SomeClass(); zParticularly if the class contains pointers and the constructor contains calls to new, a destructor needs to be defined Õe.g., SomeClass() { A = new int[20]; } ~SomeClass() { delete [] A; }

20 C++ Control Over Copy and Assignment zIn C++, the semantics of “a = b” (assignment) can be specified Õby defining the copy-assignment operator zIn C++, there is a copy constructor Õspecifies what happens during object copying, e.g., when function parameters are passed zThere is more low-level control Õshallow copy vs deep copy

21 Methods zDefines object behavior zStatic methods vs instance methods zMethod overloading Õwithin class, two methods with the same name but different signatures zMethod overriding Õsame signatures across different classes (subclass and superclass)

22 Operators zIn C++, operators like =, +, *, ==, etc. can be defined, just like methods zExample: Õclass Matrix { //... Matrix operator+(Matrix m) { … } // … } Õc = a + b; // equiv to c = a.operator+(b);

23 Method Binding zLet Teacher be a subclass of Employee ÕAlso, suppose promote() is a method defined in both classes zEmployee variables can refer to Teachers ÕIn Java, Employee e; … e = new Teacher(); ÕIn C++, Employee *e; … e = new Teacher; ze.promote() (or (*e).promote() ) calls which promote() method?

24 Static vs Dynamic Binding zIn C++, Employee’s promote() is called ÕDetermined at compile time and deduced from the type of the variable (static binding) zIn Java, Teacher’s promote is called ÕDetermined at run-time because the actual type of the referred object is checked then (dynamic binding) * C++ uses virtual functions for dynamic binding

25 Static Binding zPointer is typed to know the base class and is ignorant of the structure or existence of the derived classes zIf 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.

26 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) {} };

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

28 C++ Run Time Binding zIf 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 virtual  If virtual, the compiler will deposit the “type field” of the class in the object

29 Virtual Functions zBase class usually defines a body for a virtual function. zInherited by derived class as default if it chooses not to override the implementation zVirtual keyword in function declaration, not in definition

30 Containers zExamples: Lists, Stacks, Files, etc. zStructures that “contain” elements zOften, the element’s type has little or nothing to do with the containers’ operations zPossible room for re-use Õunified container code for a stack of integers, a stack of webpages, a stack of strings,...

31 Java and the Object Hierarchy zAll classes extend the Object class: ÕA variable of class Object can refer to any Java object zExample: Õpublic class Stack { Object A[]; int top; // … void push(Object elt) //... }

32 C++ and Templates zTemplates allow for a generic definition Õparameterized definition, where the element type is the parameter zExample: Õtemplate class Stack { T A[MAX]; int top; public: void push(T element) // … }

33 C++ Templates z indicates that a template is being declared zT is the type name (can be a class) zUsage example: ÕStack iStack; ÕStack cStack; xwhere Cards is a user defined class zA type used as a template argument must provide the interface expected by the template

34 Defining a Template zWhen defining a template member outside of its class, it must be explicitly declared a template zExample Õtemplate Stack ::Stack()

35 C++ Standard Containers zVector : 1-D array of T zlist : double linked list of T zdequeue : double-ended queue of T zqueue : queue of T zstack : stack of T zmap : associative array of T zset : set of T zbitset : set of booleans

36 GUI Programming zIn Java, GUI is part of its development kit Õjava.awt.* is a collection of classes that support visual programming and graphics Õvisual objects (buttons, text fields, etc), layout managers, events, etc. zIn C++ Õnot part of the language Õlibraries dependent on platform (e.g., MFCs and Motif)


Download ppt "OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors."

Similar presentations


Ads by Google