The Notion of a Class and Some Other Key Ideas (contd.) Questions:

Similar documents
Extending Classes (contd.) (Chapter 15) Questions:

Extending Classes (contd.) (Chapter 15) Questions:

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II

Inheritance, and Polymorphism.

CS3157: Advanced Programming. Outline

STRUCTURING OF PROGRAM

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

CS2141 Software Development using C/C++ C++ Basics

CE221 Programming in C++ Part 1 Introduction

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Object Reference and Memory Allocation. Questions:

C++ Scope Resolution Operator ::

Ch02. True/False Indicate whether the statement is true or false.

ITI Introduction to Computing II

Object Oriented Design

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Data Abstraction. Hwansoo Han

Short Notes of CS201

Java Object Oriented Design. CSC207 Fall 2014

ITI Introduction to Computing II

Introduction to Programming Using Java (98-388)

CS201 - Introduction to Programming Glossary By

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Array. Prepared By - Rifat Shahriyar

Classes, The Rest of the Story

ECE 462 Midterm Exam 1. 10:30-11:20AM, September 21, 2007

Absolute C++ Walter Savitch

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

CS260 Intro to Java & Android 03.Java Language Basics

Object Oriented Design

W3101: Programming Languages C++ Ramana Isukapalli

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

CSE 303: Concepts and Tools for Software Development

What about Object-Oriented Languages?

1 Shyam sir JAVA Notes

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Computer Programming : C++

9 Working with the Java Class Library

Polymorphism Part 1 1

2 nd Week Lecture Notes

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

AN OVERVIEW OF C++ 1

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Chapter 1: Object-Oriented Programming Using C++

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Fast Introduction to Object Oriented Programming and C++

Java: introduction to object-oriented features

Bruce Merry. IOI Training Dec 2013

OBJECT ORİENTATİON ENCAPSULATİON

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Computer Science II (20073) Week 1: Review and Inheritance

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Introduction to C++ Systems Programming

Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7

10. Functions (Part 2)

Programming overview

CS 162, Lecture 25: Exam II Review. 30 May 2018

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Functions and Recursion

Class, Variable, Constructor, Object, Method Questions

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

ITI Introduction to Computing II

Inheritance and Polymorphism

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Chapter 10 Classes Continued. Fundamentals of Java

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

A Short Summary of Javali

index.pdf January 21,

ITI Introduction to Computing II

CSCE3193: Programming Paradigms

Recharge (int, int, int); //constructor declared void disply();

Comments are almost like C++

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

CS201- Introduction to Programming Current Quizzes

Points To Remember for SCJP

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Inheritance and Interfaces

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Variables. Data Types.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

4. Structure of a C++ program

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Programming Language Concepts: Lecture 2

Comp-304 : Object-Oriented Design What does it mean to be Object Oriented?

Data Structures using OOP C++ Lecture 3

Declarations and Access Control SCJP tips

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

a. a * c - 10 = b. a % b + (a * d) + 7 =

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Transcription:

The Notion of a Class and Some Other Key Ideas (contd.) Questions: 1

1. WHO IS BIGGER? MR. BIGGER OR MR. BIGGER S LITTLE BABY? Which is bigger? A class or a class s little baby (meaning its subclass)? 2

2. When you extend a class in C++ in order to define a subclass, the syntax for the subclass header must have what elements in it? 3

3. When you extend a class in Java in order to define a subclass, the syntax for the subclass header must have what keyword in it? 4

4. What is one of the first things that a subclass constructor must do in both C++ and Java? 5

5. How does a C++ subclass constructor invoke its superclass constructor? 6

6. How does a Java subclass constructor invoke its superclass constructor? 7

7. Is it necessary for a subclass constructor to invoke its superclass constructor? 8

Packages in Java (Section 3.9) The Java platform consists of packages of related classes and interfaces. For example, all the classes that deal with I/O are in thejava.io package; the utility classes are all grouped in the java.util package; etc. 9

import java.util.*; public class Test { public static void main( String[] args ) { int[] arr = new int[1000000]; for ( int i=0; i<1000000; i++ ) arr[i] = (int) ( 1000000 * Math.random() ); long starttime = System.currentTimeMillis(); Arrays.sort( arr ); long difftime = System.currentTimeMillis() - starttime; System.out.println( "\n\nsort time in milliseconds: " + difftime ); 10

In order to create your own packages, the first executable statement in your class definition must be statement package packagename; 11

Namespaces in C++ (Section 3.10) The modularity that one gives to Java software through the mechanism of packages can be given to C++ software through the mechanism of namespaces. The basic syntax for encapsulating code in a namespace is namespace ModuleName { // code All of the code in a given namespace can be in one file, or distributed over multiple files. If more than one file is involved, the code in each file must be encapsulated in the manner shown above. 12

A namespace creates a scope. The identifiers declared in a given namespace cannot be accessed directly outside that namespace without the scope operator ::. For example, if we create namespace module by namespace Module1 { void foo() { cout << "Module1 foo() invoked" << endl; To access the function foo(), we must invoke it by Module1::foo(); 13

Since it can get to be tedious to always have to precede the name of a function by its module name, C++ allows us to employ the using directive, as in int main() { using namespace Module1; foo(); 14

#include <string> #include <iostream> using namespace std; //(A) namespace Module1 { void foo(); // this is only a declaration // definition will come later namespace Module2 { void foo() { cout << "Module2 foo() invoked" << endl; namespace Module3 { using namespace Module1; // has foo //(B) using namespace Module2; // also has foo, but //(C) // no problem at this point void bar() { cout << "Module3 bar() invoked" << endl; namespace Module4 { void foo() { cout << "Module4 foo() invoked" << endl; namespace Module5 { void bar() { cout << "Module5 bar() invoked" << endl; // foo of Module1 defined outside the namespace Module1. Must // therefore use namespace-qualified name for foo: 15

void Module1::foo() { cout << "Module1 foo() invoked" << endl; // The global foo: void foo() { cout << "top level foo() invoked" << endl; //Addition to Module5: namespace Module5 { void hum() { cout << "Module5 hum() invoked" << endl; int main() { //This statement invokes global foo() foo(); Module1::foo(); Module2::foo(); //(D) //(E) //(F) //The following statement, if uncommented, results //in compiler error because Module1 and Module2 //both have foo() // Module3::foo(); //(G) Module3::bar(); //(H) using namespace Module4; 16

//The following statement, if uncommented, results //in compiler error because foo() of Module4 //conflicts with the global foo() // foo(); //(I) //But the following statement is okay since it uses //the scope operator for invoking the global foo() ::foo(); using namespace Module5; bar(); hum(); return 0; //(J) //(K) //(L) 17

The program produces the following output: top level foo() invoked Module1 foo() invoked Module2 foo() invoked Module1 foo() invoked Module3 bar() invoked Module5 bar() invoked Module5 hum() invoked 18

Using Declaration Versus Using Directive While a using directive makes all its names merely available to the current scope, a using declaration actually declares a specific namespace name in the current scope. 19

//Namespaces2.cc namespace Module1 { class X {; class Y {; namespace Module2 { class X {; class Y {; int main() { using Module1::X; X x1; // using Module2::X; // ERROR, name conflict X x2; return 0; 20

Which Namespace Owns Names Imported from Another Namespace? If one namespace is imported into another named namespace, the member names of the former can be thought of as belonging to the latter. 21

//Namespaces3.cc #include <iostream> using namespace std; namespace Module1 { class X {; namespace Module2 { void foo(){ cout << "foo of Module2 invoked" << endl; void bar(){ cout << "bar of Module2 invoked" << endl; namespace Module3 { using namespace Module1; typedef X Y; using Module2::foo; class Z {; int main() { Module3::X x; Module3::Y y; 22

Module3::foo(); // Module3::bar(); // ERROR. No bar in Module3. return 0; 23

Using Declarations and Directives Have Scope Just like any other declaration, using directives and declarations have block scope. A block is a section of code delimited by curly brackets. This fact can be used to localize the visibility of the names introduced into a program by either a using directive or a using declaration. 24

//Namespaces.cc #include <iostream> using namespace std; namespace Module1 { typedef int Type; Type foo( Type arg ) { return arg; namespace Module2 { typedef double Type; Type foo( Type arg ) { return arg; int main() { { using namespace Module1; Type x = 100; { // int cout << foo( x ) << endl; // 100 using namespace Module2; Type x = 3.14; // double 25

{ { cout << foo( x ) << endl; // 3.14 using Module1::foo; cout << foo( 100 ) << endl; // 100 using Module2::foo; cout << foo( 3.14) << endl; // 3.14 return 0; 26

Nesting Namespaces and Namespace Aliases It is possible to nest namespaces to any depth. If an inner namespace contains a name that is identical to an outer namespace, the inner name hides the outer name. Also, the namespace-qualified name of an inner namespace starts with the name of the outermost namespace, followed by the scope operator, followed by the name of the next-to-the-outermost namespace, followed by the scope operator, etc., until reaching the inner namespace. 27

// NamespaceNested.cc #include <iostream> #include <string> using namespace std; namespace N1 { typedef int Type; namespace N2 { typedef int* Type; namespace N3 { typedef string Type; namespace N4 { typedef string* Type; int main() { using namespace N1; Type x = 10; // Type is int cout << x << endl; // 10 28

N1::N2::Type p = &x; // Type is int* cout << *p << endl; // 10 N1::N2::N3::Type str( "hello" ); cout << str << endl; N1::N2::N3::N4::Type q = &str; cout << *q << endl; namespace N_FOUR = N1::N2::N3::N4; N_FOUR::Type ptr = &str; cout << *ptr << endl; // Type is string // "hello" // Type is string* // "hello" // namespace alias // "hello" return 0; 29

Unnamed Namespaces When defining a namespace, you are allowed to omit the name of the namespace: namespace { int buffer; class X; void foo(); typedef string* T; The compiler internally generates a unique name for such a namespace. Furthermore, a using directive is automatically assumed for an unnamed namespace. 30

So, in effect, an unnamed namespace declaration is equivalent to namespace ---UNIQUE_NAME--- { int buffer; class X; void foo(); typedef string* T; using namespace ---UNIQUE_NAME---; 31

Names introduced into the current scope through an unnamed namespace possess internal linkage the same linkage as for a global name that is declared to be static. When you declare a global name in file A to be static, its scope is limited to file A. It cannot be linked to from a file B by the use of extern declaration in file B. That allows you to use the same name in file B for a different purpose without fear of creating a name clash with file A. An unnamed namespace is meant to be a cleaner way of achieving the same effect. The use of the global static in C++ programs for achieving internal linkage for a name is being deprecated. 32

Koenig Lookup for Unqualified Function Names So far we have seen three different ways in which the namespace definition of a name can be accessed outside the namespace. We can either use a namespace-qualified name, or resort to a using declaration, or to a using directive in the manner shown earlier. For unqualified function names, there is yet another way that allows the system to access the namespace definition of a function name through Koenig lookup. 33

//Koenig.cc #include <iostream> using namespace std; namespace Module1 { class X {; void foo( X xobj ) { cout << "Module1 s foo(x) invoked"; namespace Module2 { void foo( Module1::X xobj ) { cout << "X s foo(x) invoked"; void foo( int i ) { cout << "global foo(int) invoked"; int main() { Module1::X xob; foo( 1 ); foo( xob ); return 0; // global foo(int) invoked // Module1 s foo(x) invoked 34

Access Control for Class Members (Section 3.11) Every member of a class has associated with it an access control property. In C++, a member can be private, protected, or public. In addition to these three, Java also allows for the access control property of a member to be package. When the access control modifier is left unspecified for a class member in Java, it is of type package. 35

Access Control in C++: All members of a C++ class are private unless declared explicitly to be otherwise. Public members of a class are accessible to all other classes and functions. Members that are private to a class can be accessed by only those functions that are defined specifically for that class. The access control modifier protected is used for a member if we wish for that member to be accessible to only the subclasses of that class. (A protected member of a class acts like a public member for the subclasses derived from that class, but like a private member for the rest of the program.) 36

The private members of a class are also accessible to the friends of that class. 37

//Friend.cc #include <iostream> class Y; //(A) class X { int m; int n; public: X( int mm, int nn ) { m = mm; n = nn; friend Y; friend void print( X* ); ; //(B) //(C) class Y { X* x; int t; public: Y( X* xobj ) { x = xobj; t = x->m + x->n; //(D) int get_t() { return t; ; void print( X* ptr ) { cout << ptr->m << " " << ptr->n << endl; //(E) 38

int main() { X* ptr = new X(100, 200); Y y( ptr ); cout << y.get_t() << endl; // 300 print( ptr ); // 100 200 return 0; 39

A friend declaration may be placed in any section of a class, private, protected, or public. It carries the same meaning regardless of where it appears. 40

Access Control in Java: In addition to the modifiers public, private, and protected, Java has one more: package. The modifiers public and private carry the same meaning in Java as they do in C++. The modifier protected also carries the same meaning, except that such members are like public members in the same package. In other words, a protected class member will be accessible inside all classes in the same package, but to only the subclasses in other package. 41

When no access modifier is specified in Java, that means the member is of type package. Such members are no different from public members within the same package. But they act like private members with respect to other packages. 42

Abstract Classes and Interfaces (Section 3.12) Abstract classes are very important to object-oriented programming. While the notion of an abstract class is common to both C++ and Java, the latter also supports a variant thereof interfaces. A Java interface is an abstract class that is not allowed to contain any implementation code at all for any of the member functions. An interface is also not allowed any data members that can be given values on a per object basis. 43

Why abstract classes are useful: An abstract class can lend organization to the other classes in a class hierarchy. An abstract class can represent a specialized behavior, which when mixed with the other classes gives us classes with that behavior. Abstract classes can help build up an implementation incrementally. 44

An abstract class can help with knowledge organization in an OO program by serving as a root class of a hierarchy of other concrete classes and thus pull together what might otherwise be disparate bits of knowledge encapsulated in the subclasses. Shape Circle Rectangle... 45

46

C++: class Shape { public: virtual double area( ) = 0; virtual double circumference() = 0; //... ; //(A) //(B) JAVA: abstract class Shape { abstract public double area( ); abstract public double circumference(); //... 47

interface Collection { public boolean add( Object o ); public boolean remove( Object o ); // other methods The methods declared in an interface are always public, implicitly so if their access privilege is not so stated. 48

Comparing Objects (Section 3.13) The basic issues in object comparison relate to what can be compared; and how to compare. class Apple { class Orange { Taste taste; Taste taste; Size size; Size size; Weight wt; Weight wt; //... //... ; ; 49

There are two kinds of comparisons that one can make for class type objects: We may wish to know whether or not two objects are identical on the basis of equal values for one or more of the data members. The result of such a comparison is either true or false. Or, we may wish to know whether one object is smaller than, equal to, or greater than another object, again on the basis of the values for one or more data members of the objects involved. 50

In C++, the first kind of comparison is yielded typically by the == operator. The programmer has to overload this operator for a given class. The second type of comparison in C++ is implemented by defining an appropriate comparison function that returns the three values needed. 51

Our discussion so far on object comparison has been centered primarily on a comparison of two objects on the basis of their content, meaning on the basis of the values of one or more the data members of the objects. Java adds an additional twist to this it allows object comparisons on the basis of equality of reference. Two objects are equal on the basis of equality of reference if they are the same object in the memory. 52

In Java, comparison of two objects on the basis of equality of reference is carried out by the == operator. And a comparison on the basis of content can be carried out by a programmersupplied definition for the equals() method that every class in Java inherits from the root class Object. 53

class X { int p; X( int m ) { p = m; //... X x1 = new X( 10 ); X x2 = x1; x1 == x2; // true X x1 = new X( 10 ); X x2 = new X( 10 ); x1 == x2; // false If you do not supply your own override definition forequals thatxinherits from Object, comparisons using equals behave in exactly the same manner as comparisons using ==: 54

X x1 = new X( 10 ); X x2 = x1; x1.equals( x2 ); X x3 = new X( 10 ); x1.equals( x3 ); // true // false 55

//EqualityTest.java class X { int p; int q; X( int m, int n ) { p = m; q = n; boolean equals( X other ) { return p == other.p; class Test { public static void main( String[] args ) { X x1 = new X( 10, 100 ); // x1 and X x2 = new X( 10, 10000 ); // x2 look very differen if ( x1.equals( x2 ) ) // but they are equal System.out.println( "x1 and x2 are equal" ); 56

The Java platform also uses the notion of natural ordering for comparing class type objects. The objects of a Java class exhibit natural ordering if the class has implemented the java.lang.comparable interface. Such a class must provide an implementation for the compareto method referred to as the class s natural comparison method that can then be used by the algorithms and the data structures for comparing data objects. The compareto method must return a negative integer, a zero, or a positive integer if the object on which it is invoked is less than, equal to, or greater than the argument object. 57

Many of the system supplied classes in Java possess natural ordering. These include String, Integer, Float, Double, Date, File and many others. For the String class, the natural order is lexicographic; it is chronological for the Date class; lexicographic on the pathname for the File class, etc. 58

Template Classes A templatized C++ program can work with different types of data types. For example, a templatized C++ linked-list can be used to hold elements of type int, double, char,etc. class X{ T datum; public: // constructor, etc. ; // type T not known in advance 59

template <class T> class X { T datum; public: X( T dat ) : datum( dat ) { T getdatum(){ return datum; ; 60

#include <string> #include <iostream> template <class T> class X { T datum; public: X( T dat ) : datum( dat ) { T getdatum(){ return datum; ; int main() { int x = 100; X<int> xobj_1( x ); double d = 1.234; X<double> xobj_2( d ); string str = "hello"; X<string> xobj_3( str ); string ret1 = xobj_3.getdatum(); cout << ret1 << endl; // output: hello // int ret2 = xobj_3.getdatum(); // Error 61