0% found this document useful (0 votes)
13 views45 pages

Lecture 2 - Encapsulation Data Hiding

The document discusses key concepts of object-oriented programming, focusing on encapsulation, constructors, destructors, and memory management in C++ and Java. It explains how constructors initialize objects, the role of destructors in memory management, and the use of pointers and references. Additionally, it covers inline functions and object assignment, highlighting differences between C++ and Java.

Uploaded by

malihakhan1030
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views45 pages

Lecture 2 - Encapsulation Data Hiding

The document discusses key concepts of object-oriented programming, focusing on encapsulation, constructors, destructors, and memory management in C++ and Java. It explains how constructors initialize objects, the role of destructors in memory management, and the use of pointers and references. Additionally, it covers inline functions and object assignment, highlighting differences between C++ and Java.

Uploaded by

malihakhan1030
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Lecture Two

Encapsulation / Data Hiding


Implemented through Class

© Dr. Mohammad Mahfuzul Islam, PEng


Professor, Dept. of CSE, BUET
Constructor
Object Creation may require some sort of initialization. Constructor Method performs the tasks of initialization.
A class’s constructor is called automatically when an object of that class is created.
A constructor function has the same name as the class of which it is a part and has no return type.
Constructor may have or may not have arguments. void MyClass::show(){
cout << a << '\n';
#include <iostream>
}
using namespace std;

C++ Code
int main(){
class MyClass {
MyClass ob1, ob2(10);
int a = 0;
public:
ob1.show();
MyClass(){cout << "No Argument Constructor" << endl;}
ob2.show();
MyClass(int newA); // constructor
return 0;
void show();
}
};
Output:
No Argument Constructor
MyClass::MyClass(int newA){ Constructor with Argument
cout << "Constructor with Argument" << endl; 0
a = newA; 10
}
2
Constructor
class MyClass {
private int a = 0;
MyClass(){System.out.println("No Argument Constructor");}
MyClass(int newA){
System.out.println("Constructor with Argument");
a = newA;
}
public void show() {
System.out.println(a);
} Output:

Java Code
} No Argument Constructor
Constructor with Argument
public class Main { 0
10
public static void main(String[] args){
MyClass ob1 = new MyClass();
MyClass ob2 = new MyClass(10);

ob1.show();
ob2.show();
}
}
3
Constructor – Object Cloning
#include <iostream>
using namespace std; int main() {
Box myBox(5, 3, 2);
class Box{ Box myClone(myBox);
double length;
double width; cout << "Box Volume: " << myBox.volume() << endl;
double height; cout << "Clone Volume: " << myClone.volume() << endl;
public: }
Box(double l, double w, double h){
length = l;

C++ Code
width = w;
height = h;
} Output:
Box(const Box& ob){ Box Volume: 30
length = ob.length; Clone Volume: 30
width = ob.width;
height = ob.height;
}
double volume(){
return length * width * height;
}
};
4
Constructor – Object Cloning
class Box{

Java Code
private double length;
private double width;
private double height;

public Box(double l, double w, double h){


length = l;
width = w; public class Main {
height = h; public static void main(String[] args) {
} Box myBox = new Box(5, 3, 2);
Box myClone = new Box(myBox);
public Box(Box ob){
length = ob.length; System.out.println("Box Volume: " + myBox.volume());
width = ob.width; System.out.println("Clone Volume: " + myClone.volume());
height = ob.height; }
} }

public double volume(){ Output:


return length * width * height; Box Volume: 30
} Clone Volume: 30
};
5
Destructor
While working with object, some actions may be performed when an object is destroyed, e.g., freeing
the memory allocated by the object. This destructor method is called when an object is destroyed.
Local objects are destroyed when they go out of scope. Global objects are destroyed when the program
ends.
#include <iostream> myclass::myclass(){
using namespace std; cout << "In constructor\n";
a = 10;
class myclass { }
int a;
Output:
public: int main(){
In constructor
myclass(); myclass ob;
10
~myclass(){cout << "Destructing……\n";}; ob.show();
Destructing……
void show(){cout << a << endl;}; return 0;
}; }

✓ Java doesn’t have any Destructor method.


✓ The garbage collector inherently handles memory allocation and release.
6
Object Pointer
Object pointer stores address of the object.
When a pointer to the object is used, the arrow operator (→) is employed rather than dot (.) operator.
Like pointers to other types, an object pointer, when incremented, will point to the next object of its type.

#include <iostream> int main(){


using namespace std; MyClass ob(120);
MyClass *p;
class MyClass {
int a; p = &ob;
public: cout << "Object Value:" << ob.getA() << endl;
MyClass(){ a = 10;} cout << "Value using pointer:" << p->getA() << endl;
MyClass(int x){ a = x;};
int getA() {return a;}; return 0; Output:
}; } Object Value:120
Value using pointer:120

There is no pointer operator in Java.


7
The this Pointer / Reference
➢A special pointer (C++) or reference (Java) called this represents the working object and is
automatically passed to any member function when it is called.
➢No programmer uses the this pointer / reference to access a class member because the shorthand
form is much easier.
Message Message::updateMessage(string msg) {
#include <iostream> this->msg = msg;
return *this;

C++ Code
#include <string>
using namespace std; }

class Message { void Message::displayMessage() {


string msg; cout << "Message: " << this->msg << endl;
public: }
Message(string msg) {
this->msg = msg; int main() {
} Message msg("Hello, World!");
Message updateMessage(string msg);
void displayMessage(); msg.displayMessage();
}; msg = msg.updateMessage("New Message.");
Output: msg.displayMessage();
Message: Hello, World! }
Message: New Message. 8
The this Pointer / Reference
public class Main {
The this keyword in Java is a reference variable that
public static void main(String[] args) {
refers to the current object. Message msg = new Message("Hello, World!");
a = newA; => this.a = newA;
msg.displayMessage();
class Message { msg = msg.updateMessage("New Message.");
private String msg; msg.displayMessage();

Java Code
}
public Message(String msg) { }
this.msg = msg;
}

public Message updateMessage(String msg) {


this.msg = msg;
return this; Output:
} Message: Hello, World!
Message: New Message.
public void displayMessage() {
System.out.println("Message: " + this.msg);
}
} “this” means “current object”.
9
Using new and delete in C++ Pointer
➢ C++ uses new operator for dynamically allocating memory (C uses malloc()).
General form: p-var = new type;
p-var = new type (initial value);
p-var = new type [size];
➢ C++ uses delete operator for releasing dynamically allocating memory (C uses free()).
General form: delete p-var; int main(){
Samp *p = new Samp;
delete [] p-var;
Samp *q = new Samp(3, 4);
#include <iostream> Samp *r = new Samp[2];
using namespace std; cout << "Product: " << p->getProduct() << endl;
cout << "Product: " << q->getProduct() << endl;
class Samp{ for(int i = 0; i < 2; i++){
int a, b; r[i] = Samp(i+1, i+2);
public: cout << r[i].getProduct() << endl;
Samp(){ a = 0; b = 0;} }
Samp(int x, int y){ a = x; b = y;} delete p; Output:
int getProduct(){ return a * b;} delete q; Product: 0
}; delete[] r; Product: 12
return 0; 2
} 6 10
Object Declaration
C++ Java
length
Box myBox; width Box myBox;
height
myBox
myBox

Box myBox = new Box();


Box *pBox;
pBox
length
Box *pBox = new Box; myBox
width
height
length
width
pBox
height
11
Reference in C++
➢A reference is an implicit pointer that acts like another
name of a variable. A reference can be used in Three ways:

✓A reference can be passed to a function


Passing Reference to a function
✓A reference can be returned by a function #include <iostream>
using namespace std;
✓An independent reference can be created.

Use of Reference
#include <iostream> void f(int &p) {
p = 100;

Use of Pointer
using namespace std;
}
void f(int *p) {

C++ Code
*p = 100; int main(){
} int a = 10;
f(a);
int main(){ cout << "a: " << a << endl;
int a = 10; return 0;
f(&a); }
cout << "a: " << a << endl;
return 0; Output:
} a: 100
12
Reference in C++

Passing Reference to a function


➢When a reference parameter is used, the compiler automatically passes the address of
the variable as the argument. There is no need to manually generate the address of the
argument by preceding it with an & (in fact, it is not allowed).
➢ Within the function, the compiler automatically uses the variable pointed to by the
reference parameter, no need to employ *.
➢ A reference parameter fully automates the call-by-reference parameter passing
mechanism.

C++ Code
void f(int &n){
n = 100;
n++;
}

➢ In the above example, instead of incrementing n, this statement increments the value of the
variable being referenced (in this case, a).

13
Reference in C++

A Reference returned by a function

➢Very useful for overloading certain types of ➢Allow a function to be used on the left side of an
operator. assignment statement.
int main(){
Coord P(10, 20); #include <iostream>
#include <iostream> P.show(); using namespace std;
using namespace std; ++P;
P.show(); int x;
class Coord{ return 0;
int x, y; } Output:

C++ Code
public: int &f(){ BUT
Coord(int a, int b){x = a; y = b;} return x; 100 int &f(){
Coord& operator++(){ } int x;
x++; return x;
y++;
Output: }
(10,20) int main(){
return *this;
} (11,21) f() = 100;
void show() { cout << x << endl;
cout << "(" << x << "," << y << ")" << endl; return 0;
} }
};
14
Reference in C++

Independent Reference
➢ An independent reference is a reference variable that in all effects is simply another name for
variable.
➢Because reference cannot be assigned new values, an independent reference must be initialized
when it is declared.
#include <iostream>
using namespace std;
The independent reference ref
int main(){
Output: serves as a different name for x.
C++ Code

int x;
int &ref = x; 100, 100
Independent reference cannot be a
constant like
x = 10;
const int &ref = 10;
ref = 100;
cout << x << ", " << ref << endl;

return 0;
}
15
In-line Function
In-line Function: Like macros in C, In-line functions are not actually called,
rather are expanded in line, at the point of each call. #include <iostream>
using namespace std;
Advantage:

C++ Code
inline int even(int x){
➢ In-line function has no overhead associated with the function call and return (x % 2 == 0);
return mechanism, so much faster than the normal function calls. }

➢ In parameterized macros, it is easy to forget extra parentheses are needed. int main(){
In-line function is a structure way to expand short function in line and if (even(10))
prevent the problems of parameterized macros. cout << "Even" << endl;
return 0;
Disadvantage: If in-line functions are too large and called too often, program }
Output:
grows larger. Therefore, only short functions are declared in-line. Even

Inline specifier is a request, not a command to the compiler:


Some compiler will not inline a function if it contains a static variable, loop, switch or goto. If any inline
restriction is violated, the compiler is free to generate a normal function.
16
Automatic In-line Function

Automatic In-line Function: If a member’s function definition in a class is short enough, then the
function automatically becomes an in-line function. The inline keyword is no longer necessary.
✓ The same restriction that apply to a normal in-line functions apply to automatic in-line functions
within a class declaration.
int main(){
#include <iostream> Samp s1(10, 2), s2(10,3);
using namespace std;
if (s1.divisible())
class Samp{ cout << "10 is divisible by 2" << endl;
int a, b; if (s2.divisible())
public: cout << "10 is divisible by 3" << endl;
Samp(int n, int m){a = n; b = m;}
int divisible(){ return !(a%b);} return 0;
}; }

Output:
10 is divisible by 2
17
In-line function in Java
Java doesn’t support inline command. But in Java, the compiler can perform in-lining when
the small final method is called.
Because final methods can't be overridden by subclasses, and the call to a final method is
resolved at compile time. class Cylindar extends Figure{
private double height;
class Figure{
Cylindar(double newRadius, double newHeight){
final private double pi = 3.14159;
setRadius(newRadius);
private double radius;
// setPI(3.14159);

JAVA Code
height = newHeight;
// public void setPI(double newPI){ pi = newPI;}
}
public double getPI(){ return pi;}
public void setRadius(double newRadius){ radius = newRadius;}
/* public double circleArea(){
public double getRadius(){ return radius;}
return pi*radius*radius;
} */
final public double circleArea(){return pi*radius*radius;}
}
public double cylindarVolume(){
return circleArea()*height;
}
} 18
Object Assignment
One object can be assigned to another provided that both objects are of the same type.
By default, when one object is assigned to another, a bitwise copy of all the data members is made.
#include <iostream>
int main(){
using namespace std;
MyClass ob1, ob2;
class MyClass{ YourClass ob3;
int a, b;
public: ob1.setValue(10, 20);
void setValue(int n, int m){a = n; b = m;} ob2 = ob1; //Ok
void show(){ // ob3 = ob1; //Compilation Error
cout << a << ", " << b << endl;
ob1.show();
}
}; ob2.show();

class YourClass{ return 0;


int a, b; }
public:
void setValue(int n, int m){a = n; b = m;}
void show(){ Output:
cout << a << ", " << b << endl; 10, 20
} 10, 20
};
19
Problem with Object Assignment in C++
When an object pointing to dynamic memory allocation is assigned to another object
➢ both object share the same memory.
➢ Destroying one object release the common memory and possibly cause program crash.

p strtype s1(“This is a test.”);


len
s1

s2 = s1; This is a test.

When either s1 or s2 is destroyed, this memory


location is also destroyed => program crashed.
p
len
s2
20
Problem with Object Assignment in C++
#include <iostream> int main(){
#include <cstring> ObAssign ob1("Hello World"), ob2("like C++");
#include <cstdlib>
using namespace std; ob1.show();
ob2.show();
class ObAssign{ ob2 = ob1; // This will cause a problem
char *str; ob2.show();
int len;
public: return 0;
ObAssign(char *s){ } Program name:
len = strlen(s); ObAssignProblem.cpp
str = (char *)malloc(len + 1);
Output:
Hello World:11
strcpy(str, s); Like C++:8
} Hello World:11
~ObAssign(){ Freeing memory
cout << "Freeing memory" << endl; Freeing memory
free(str); ObAssignProblem(1217,0x109ed5600) malloc: *** error for
} object 0x7f9842f059d0: pointer being freed was not
allocated
void show(){ ObAssignProblem(1217,0x109ed5600) malloc: *** set a
cout << str << ":" << len << endl; breakpoint in malloc_error_break to debug
} zsh: abort ./"ObAssignProblem"
}; 21
Solution to the Object Assignment Problem in C++
int main(){
Solution 1: Use of Pointer ObAssign *ob1 = new ObAssign("Hello World");
#include <iostream> ObAssign *ob2 = new ObAssign("Like C++");
Without Pointer: #include <cstring>
p #include <cstdlib> ob1->show();
using namespace std; ob2->show();
Len = 11 ob2 = ob1;
Hello World class ObAssign{
ob1 ob2->show();
char *str;
int len; return 0;
p public: }
ObAssign(char *s){
Len = 11
len = strlen(s); Output:
ob2 str = (char *)malloc(len + 1); Hello World:11
strcpy(str, s); Like C++:8
With Pointer: } Hello World:11
~ObAssign(){
Hello World cout << "Freeing memory" << endl;
ob1 free(str);
p }
No Execution of
void show(){ Destructor.
Len = 11 cout << str << ":" << len << endl;
ob1 } Acceptable??
};
22
Solution to the Object Assignment Problem in C++
~ObAssign() {
#include <iostream> Solution 2: cout << "Freeing memory" << endl;
#include <cstring>
#include <cstdlib>
Copy Assignment free(str);
Operator }
using namespace std;
void show() {
class ObAssign {
cout << str << ":" << len << endl;
char *str;
}
int len;
};
public:
ObAssign(char *s) {
int main() {
len = strlen(s);
ObAssign ob1("Hello Word"), ob2("like C++");
str = (char *)malloc(len + 1);
strcpy(str, s);
ob1.show();
}
ob2.show();
ObAssign& operator=(const ObAssign &obj) {
if (this == &obj) {
ob2 = ob1; // Assignment operator is invoked
return *this; // self-assignment
ob2.show();
} // e.g., ob1 = ob1
free(str); Output:
return 0; Hello World:11
len = obj.len;
} like C++:8
str = (char *)malloc(len + 1);
strcpy(str, obj.str); Hello World:11
return *this; Freeing memory
} Freeing memory
23
Passing Object as an Argument in C++
Parameter passing, by default, is called by value. That is a bitwise copy is made.
New object created in the function does not call constructor, but destructor is called.
#include <iostream> void sqrOb(ObArg ob){
using namespace std; ob.setA(ob.getA() * ob.getA());
cout << "Inside sqrOb: " << ob.getA() << endl;
class ObArg{ }
int a;
public: int main(){
ObArg(int n){ ObArg ob1(10);
a = n; cout << "Before sqrOb: " << ob1.getA() << endl;
cout << "Constructing..." << endl; sqrOb(ob1);
} cout << "After sqrOb: " << ob1.getA() << endl;
return 0;
~ObArg(){ }
cout << "Destructing..." << endl; Output:
} Constructing...
Before sqrOb: 10
void setA(int n){ a = n; } Inside sqrOb: 100
int getA(){ return a; } Destructing...
}; After sqrOb: 10
Destructing... 24
Problem with Passing Object as an Argument in C++
If the object used as the arguments allocates dynamic memory and free the memory then the
destructor function is called and the original object is damaged.
#include <iostream> int main(){
using namespace std; ObArgProb ob1(10);

class ObArgProb{ cout << "Before: " << ob1.getP() << endl;
int *p; cout << "Result: " << negateP(ob1) << endl;
public: cout << "After: " << ob1.getP() << endl;
ObArgProb(int n){ return 0;
p = (int *)malloc(sizeof(int)); }
*p = n;
cout << "Constructing..." << endl; Output: Program name:
} Constructing... ObArgProb.cpp
~ObArgProb(){ Before: 10
cout << "Destructing..." << endl; Result: -10
free(p); Destructing...
} After: 10
int getP(){ return *p; } Destructing...
}; ObArgProb(3214,0x11af7d600) malloc: *** error for object
0x7f933b004a50: pointer being freed was not allocated
int negateP(ObArgProb ob){ ObArgProb(3214,0x11af7d600) malloc: *** set a breakpoint
return -ob.getP(); in malloc_error_break to debug
} zsh: abort ./"ObArgProb"
25
Solution to Object Passing Problem in C++
Solution 1: Using Call by Reference

Solution 1(a): Using Pointer Solution 1(b): Using Reference


Output:
int negateP(ObArgProb *ob){ Constructing...
return -ob->getP(); Before: 10 int negateP(ObArgProb &ob){
} Result: -10
return -ob.getP();
After: 10
int main(){ Destructing...
}
ObArgProb ob1(10);

cout << "Before: " << ob1.getP() << endl;


cout << "Result: " << negateP(&ob1) << endl; ob
cout << "After: " << ob1.getP() << endl;
p 10
return 0;
}
Ob1

Copy address of the Object, rather that copying


the object itself. 26
Solution to Object Passing Problem in C++
Solution 2: Using Copy Constructor ~ObArgProb(){
cout << "Destructing..." << endl;
Output: free(p);
#include <iostream>
Constructing... }
using namespace std; Before: 10 int getP(){ return *p; }
Result: Copying... };
class ObArgProb{ -10
int *p; Destructing...
After: 10
int negateP(ObArgProb ob){
public:
Destructing... return -ob.getP();
ObArgProb(int n){
}
p = (int *)malloc(sizeof(int));
*p = n; int main(){
cout << "Constructing..." << endl;
ObArgProb ob1(10);
}
cout << "Before: " << ob1.getP() << endl;
// Copy constructor
cout << "Result: " << negateP(ob1) << endl;
ObArgProb(const ObArgProb &ob){ cout << "After: " << ob1.getP() << endl;
p = (int *)malloc(sizeof(int));
*p = *(ob.p);
return 0;
cout << "Copying..." << endl;
}
}
27
Object Returning Problem in C++
When an object is returned by a function, a temporary object is created Samp input() {
which holds the return value. This object is return by the function. Samp s;
s.set("Hello, world!");
After the value has been returned, this object is destroyed. return s;
}
The destruction of this temporary object may cause unexpected side effects. int main() {
Samp ob;
#include <iostream>
#include <cstring>
using namespace std; ob = input();
ob.show();
class Samp {
return 0;
char *s;
public: }
Samp() { s = '\0'; } Output:
~Samp() {free(s); cout << "Freeing S\n";} Freeing S
void show() {cout << s << endl;} Hello, world!
void set (char *str){ ObReturnProb(1337,0x106d8c600) malloc: *** error for
s = (char *) malloc(strlen(str)+1); object 0x7f790e7059f0: pointer being freed was not
strcpy(s, str); allocated
ObReturnProb(1337,0x106d8c600) malloc: *** set a
}
breakpoint in malloc_error_break to debug
}; zsh: abort ./"ObReturnProb"
28
Solution to Object Returning Problem in C++
#include <iostream> Output: void set(char *str) {
#include <cstring> Freeing S s = (char *)malloc(strlen(str) + 1);
using namespace std; Hello, world! strcpy(s, str);
Freeing S }
class Samp { };
char *s;
public: Samp input() {
Samp() {s ='\0';} Samp s;
s.set("Hello, world!");
// Copy Assignment Operator return s;
Samp& operator=(const Samp &ob) { }
if (this == &ob) { return *this;}
s = (char *)malloc(strlen(ob.s) + 1); int main() {
strcpy(s, ob.s); Samp ob;
return *this;
} ob = input();
ob.show();
~Samp() {free(s); cout << "Freeing S\n";}
return 0;
void show() {cout << s << endl;} }
29
Use Java, Be Relaxed
Java does not have - Garbage Collection of Java: Java automatically
manages memory allocation and deallocation for
✓ Object assignment problem
objects.
✓ Problem with passing object as argument
No Destructor in Java: Java does not have any
✓ Object returning problem
destructors. Garbage collector inherently handle
memory allocation and release.
Automatic Argument Type Selection:
➢ When a primitive type argument is passed, then it is
“call by value”. Bitwise copy is made. ➢ All three C++ problems are arisen
➢ When an object is passed to a method, it is “Call by due to object destruction.
Reference”. Only creating a reference to the object.
➢ As Java does not support object
destruction, none of the problem
s1 length exists in java.
width
height
s2 Rectangle
boxName 30
Friend Function in C++
A friend function is not a member of a class but still class Truck{
has access to its private elements. int weight, speed;
public:
Three uses of friend functions Truck(int w, int s){ weight = w; speed = s;}
friend int speedGreater(Car c, Truck t);
(1) to do operator overloading; };

(2) creation of certain types of I/O functions; and int speedGreater(Car c, Truck t){
return c.speed - t.speed;
(3) one function to have access to the private }
members of two or more different classes.
int main(){
Car c(5, 70);
A friend function is a regular non-member function
Truck t(500, 60);
#include <iostream>
using namespace std; cout << "Speed Gap: " << speedGreater(c,t) << endl;

class Truck; // Forward Declaration return 0;


}
class Car{
int passenger, speed;
public:
Car(int p, int s){ passenger = p; speed = s;}
Output:
friend int speedGreater(Car c, Truck t); Speed Gap: 10
}; 31
Friend Function in C++
A member of one class can be a friend of another class.
#include <iostream> int Car::speedGreater(Truck t){
using namespace std; return speed - t.speed;
}
class Truck; //Forward Declaration
int main(){
class Car{ Car c(5, 70);
int passenger, speed; Truck t(500, 60);
public:
Car(int p, int s){ passenger = p; speed = s;} cout << "Speed Gap: " << c.speedGreater(t) << endl;
int speedGreater(Truck t);
}; return 0;
}
class Truck{
int weight, speed;
public:
Truck(int w, int s){ weight = w; speed = s;}
friend int Car::speedGreater(Truck t);
};
Java does not have a "friend" keyword or concept.
Output:
Speed Gap: 10
32
Use of static
static: Independent of object. Static member can be accessed before creation of any object and
without reference to any object.
✓ Only one copy of static variable and all the objects of its class share it.
✓ A static member cannot access non-static members of a class. WHY?
Uses:
static variable: like global variable. When object is declared, no copy of static variable is made.
static method: Restrictions of static method-
✓ Can access static variables only and call only other static methods of their class.
✓ Can't refer to this or super anyway.
✓ Static function in C implies function can be used in multiple files.
static block: Executed exactly once, when first the class is loaded. Used for initialization.
✓ Supported only in Java. C & C++ does not support.
33
Use of static
Use of static in C Use of static (variable & method) in C++
Output:
#include <stdio.h> Count: 1 int main() {
#include <iostream> StaticDemo sd;
int a = 2; Count: 2
static int b = 5; using namespace std;
Count: 3
sd.display();
Count: 4 class StaticDemo { sd.increment();
static int mult(){
a++; b++; Count: 5 static int a; StaticDemo::display();
Product: 18 // static int b = 5; Cout << sd.getProduct() << endl;
return a * b;
} static const int b = 5; return 0;
int n = 4, m = 5; }
void fun(){
static int count = 0; public:
//static void increment() {a++; b++;}
count++;
printf("Count: %d\n", count); static void increment() {a++;}
// static int getProduct(){ return n * m;}
}
int getProduct() { return n * m;}
int main(){
static void display() {
for(int i = 0; i < 5; i++){
fun(); cout << "A: " << a << " B: " << b << endl;
}
} Output:
printf("Product: %d\n", mult()); };
A: 0 B: 5
return 0;
}
int StaticDemo::a = 0; A: 1 B: 5
20 34
Use of static
Use of static in Java public class Main {
public static void main(String[] args) {
StaticDemo sd = new StaticDemo();
class StaticDemo { StaticDemo.c = 5;
static int a = 3;
static int b; for (int i = 0; i < 2; ++i) {
static int c; sd.show(40 + i);
}
static void show(int x) { // show(10);
a++; b--; StaticDemo.show(10);
System.out.print("A: " + a + " "); System.out.println("B:"+ StaticDemo.b);
System.out.print("B: " + b + " "); }
System.out.print("C: " + c + " "); }
System.out.println("X: " + x);
}
Output:
Static is Initialized.
A: 4 B: 11 C: 5 X: 40
static {
A: 5 B: 10 C: 5 X: 41
System.out.println("Static is Initialized.");
A: 6 B: 9 C: 5 X: 10
b = a * 4;
B:9
}
}
35
Use of import static in Java
import static java.lang.Math.*;
import static java.lang.System.out;
➢Use of import static allows static members of a
class or interface can be called without reference. public class Main {
public static void main(String[] args) {
double s1 = 3.0, s2 = 4.0;
int x1 = 5, y1 = 8, x2 = 6, y2 = 10;
import java.lang.Math.*;
import java.lang.System.*;
double h = hypot(s1, s2);
double dist = sqrt(pow(x1-x2, 2)+ pow(y1-y2, 2));
public class Main {
public static void main(String[] args) {
out.println("Hypotenuse: "+ h + " Dist: " + dist);
double s1 = 3.0, s2 = 4.0;
}
int x1 = 5, y1 = 8, x2 = 6, y2 = 10;
}
double h = Math.hypot(s1, s2);
double dist = Math.sqrt(Math.pow(x1-x2, 2)+ Math.pow(y1-y2, 2));
OUTPUT:
Hypotenuse: 5.0 Dist: 2.23606797749979
System.out.println("Hypotenuse: "+ h + " Dist: " + dist);
}
}

36
Use of const and mutable in C++
➢When a member function is declared as const, it cannot modify the object that invokes it.
➢mutable overrides const-ness. A mutable member can be modified by a const member function.
➢Non-Member function cannot be const.
#include <iostream> int main() {
#include <mutex> const Demo d;
using namespace std;
d.setAB(10, 20);
class Demo { cout << "A: " << d.getA() << endl;
mutable int a; cout << "B: " << d.getB() << endl;
int b;
return 0;
public: }
Demo(){a = 0; b = 0;}
int getA() const {return a;}
int getB() const {return b;} Output:
void setAB(int x, int y) const { A: 10
a = x; B: 0
// b = y;
}
}; 37
Use of final in Java
Three uses of final keyword:
class Figure {
C++ does not have ”final" keyword.

final variable: constant, i.e., can’t be modified. final private double pi = 3.14159;
private double radius;
Can be initialized two ways:
// public void setPI(double newPI){ pi = newPI;}
✓ When declared. public void setRadius(double newRadius) { radius = newRadius; }
final public double circleArea() { return pi * radius * radius; }
final double PI =3.14159; }

✓ Assign a value within constructor. final class Cylindar extends Figure {


final private double height;
final method: can’t be overridden.
Cylindar(double newRadius, double newHeight) {
final class: can’t be inherited. setRadius(newRadius);
height = newHeight;
}
public class Main {
public static void main(String[] args) {
// public double circleArea(){ return 3.14159*radius*radius; }
Cylindar cylindar = new Cylindar(3.0, 4.0);
public double cylindarVolume() { return circleArea() * height; }
System.out.print(cylindar.cylindarVolume());
}
}
}

38
Array of Objects in C++
int main(){
Sa s1[4] = {10, 20, 30, 40};
Output: Sa s2[4] = {Sa(50), Sa(60), Sa(70), Sa(80)};
#include <iostream> s1[0] = 10 s2[0] = 50 Sa s3[3][2] = { {11, 12}, {21, 22}, {31, 32} };
#include <string> (A, 10) Sa s4[3][2] = { {Sa(41), Sa(42)}, {Sa(51), Sa(52)}, {Sa(61), Sa(62)} };
using namespace std; s1[1] = 20 s2[1] = 60 Da ob[4] = { Da("A", 10), Da("B", 20), Da("C", 30), Da("D", 40) };
(B, 20)
class Sa{ s1[2] = 30 s2[2] = 70 for (int i = 0; i < 4; i++){
int a; (C, 30) cout << "s1[" << i << "] = " << s1[i].getA() << " ";
public: s1[3] = 40 s2[3] = 80 cout << "s2[" << i << "] = " << s2[i].getA() << endl;
Sa(int n){ a = n;} (D, 40) ob[i].show();
int getA(){ return a;} s3[0][0] = 11 s4[0][0] = 41 }
}; s3[0][1] = 12 s4[0][1] = 42
s3[1][0] = 21 s4[1][0] = 51 for (int i = 0; i < 3; i++){
class Da{ s3[1][1] = 22 s4[1][1] = 52 for (int j = 0; j < 2; j++){
string name; s3[2][0] = 31 s4[2][0] = 61 cout << "s3[" << i << "][" << j << "] = " << s3[i][j].getA() << " ";
int b; s3[2][1] = 32 s4[2][1] = 62 cout << "s4[" << i << "][" << j << "] = " << s4[i][j].getA() << endl;
public: }
Da(string nam, int n){ name = nam; b = n;} }
void show(){ }
cout << "(" << name << ", " << b << ")" << endl;
}
};
39
Array of Objects in Java
class Samp { public class Main {
private int a; public static void main(String[] args) {
Samp(int n) { a = n;} int[] A = new int[4];
public int getA(){ return a;} int[] B = {11, 12, 13, 14};
} int[][] C = {{21, 22}, {23, 24}, {25, 26}};
Samp[] S = new Samp[4];
class Std{ Std[] std = {new Std("J", 101), new Std("L", 102), new Std("H", 103)};
String name;
int id; for(int i =0; i < 4; ++i){
Std(String n, int i){ name = n; id = i;} A[i] = 30 + i;
public void show(){ S[i] = new Samp(40+i);
System.out.println(name + ":" + id); }
}
} for(int i =0; i< S.length; ++i){
System.out.print(S[i].getA()+" ");
}
Output: System.out.println();
40 41 42 43 for(Std s: std){
J:101 System.out.println(s.name + ":" + s.id);
L:102 }
H:103 }
} 40
Nested Class class Inner2 {
public:
void show(string str) {
#include <iostream> cout << str << endl;
➢The scope of Nested Class is limited by the scope of #include <string> }
the enclosing class. using namespace std; };
Inner2 inner2;
➢A Nested class is a static or non-static member of the class Outer { };
enclosing class. The non-static nested class is known int a;
public:
as Inner Class. Outer(int x) { a = x; }
void show() { cout << "Outer: " << a << endl; }
➢A Inner Class class has access to the members of
enclosing class (including private members); but the void showInner(int x) {

C++ Code
enclosing class does not have access to the members Inner inner(x);
of the nested class. inner.show();
Output: }
int main() {
Outer outer(10); Outer: 10 class Inner {
outer.show(); Inner: 20 int b;
outer.showInner(20); Inner: 30 public:
Outer: 10 Inner(int y) { b = y; }
Outer::Inner inner(30); Hello from Inner2! void show() { cout << "Inner: " << b << endl; }
inner.show(); void showOuter(Outer &ob) { ob.show(); }
inner.showOuter(outer); };
outer.inner2.show("Hello from Inner2!");
return 0;
} 41
Nested Class
public class Main {
public static void main(String[] args) {
class Outer { Outer outer = new Outer(10);
private int a; outer.show();
Outer(int x) { a = x; } outer.showInner(20);
public void show() { System.out.println("Outer: " + a);}
public void showInner(int x) { Outer.Inner inner = outer.new Inner(30);

Java Code
Inner inner = new Inner(x); inner.show();
inner.show(); inner.showOuter(outer);
}
outer.inner2.show("Hello from Inner2!");
public class Inner { }
private int b; }
Inner(int y) { b = y; }
public void show() { System.out.println("Inner: " + b); }
public void showOuter(Outer ob) { ob.show(); } Output:
}; Outer: 10
Inner: 20
public class Inner2 { Inner: 30
public void show(String str) { System.out.println(str);} Outer: 10
}; Hello from Inner2!
Inner2 inner2 = new Inner2();
};
42
String Class in Java

➢String type object is immutable. Once a String object is created, its contents will not be
altered.
String myStr = new String(“This is a test.”);
String myStr = “This is a test.”;

➢Three methods of String


✓ boolean equals(secondStr)
✓ int length()
✓ char charAt(index)

➢StringBuffer and StringBuilder are peer classes of String, which allows string to be altered.

43
Command Line Arguments in Java
A Sample Program:
public class CommandLine {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("args[” + i + "]: " + args[i]);
}
}
} Output:
args[0]: this
args[1]: is
Command Line: args[2]: a
args[3]: test
……> javac CommandLine args[4]: 100
……> java CommandLine this is a test 100 -1 args[5]: -1

44
Local Variable Type Inference in Java

public class Main { String


public static void main(String[] args) {
int
String [] str1 = {"one", "two", "three"};
var str2 = "This is a test.";
?
for ( var i = 0; i < str1.length; i++) {
System.out.println("str[" + i + "]: " + str1[i]);
}
?
for( var a: str1) System.out.println(a);
System.out.println(str2); var fin = new FileInputStream("test.txt");
}
} ? Ambiguity? Why?
var x = o.getNext();

45

You might also like