Lecture 2 - Encapsulation Data Hiding
Lecture 2 - Encapsulation Data Hiding
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;
C++ Code
#include <string>
using namespace std; }
Java Code
}
public Message(String msg) { }
this.msg = msg;
}
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++
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++
➢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
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 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
(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;
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; }
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.”;
➢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
45