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

Slides:



Advertisements
Similar presentations
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Advertisements

Portability and Safety Mahdi Milani Fard Dec, 2006 Java.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Abstract Data Types and Encapsulation Concepts
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
Pointer Data Type and Pointer Variables
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Programming Languages and Paradigms Object-Oriented Programming.
Introduction to Object Oriented Programming CMSC 331.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
OOP in Java and C++ CS 123/CS 231. Outline zProgram Structure and Execution zEncapsulation and Inheritance zObjects, Variables, and Arrays zConstructors.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
COMP3190: Principle of Programming Languages
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Object Oriented Programming
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Object-Oriented Programming (Review) CS 123 Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
A First Book of C++ Chapter 12 Extending Your Classes.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Design issues for Object-Oriented Languages
Constructors and Destructors
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Andy Wang Object Oriented Programming in C++ COP 3330
Inheritance and Polymorphism
Java Primer 1: Types, Classes and Operators
Pointers, Polymorphism, and Memory Allocation
Object-Oriented Programming
Chapter 3: Using Methods, Classes, and Objects
Java Programming Language
Constructors and Destructors
SPL – PS3 C++ Classes.
Presentation transcript:

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

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

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

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

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

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.”

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

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

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

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

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

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

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

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?

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

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

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;

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

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; }

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

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)

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);

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?

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

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.

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

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

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

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

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,...

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) //... }

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) // … }

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

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

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

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)