Lecture 1 Basic Features of OOP
Lecture 1 Basic Features of OOP
Basic Features of
Object Oriented Programming (OOP)
2
I/O in C++ Programming
#include <stdio.h> #include <iostream>
int main() { using namespace std;
int a, b, sum; int main() {
char str[16]; int a, b, sum;
char str[16];
printf("Enter number 1: ");
scanf("%d", &a); cout << "Enter number 1: ";
C++ Code
printf("Enter number 2: "); cin >> a;
scanf("%d", &b); cout << "Enter number 2: ";
C Code
➢Multi-line comments
/* one or more lines of comments */
5
Some differences between C and C++
4. Local variable Local variables are declared at the start of a Local variables can be declared anywhere.
declaration block, prior to any action statement.
5. bool data type - C++ defines the bool data type and also
keywords true and false.
6
I/O in Java Programming
Notes for Java:
✓ System class of java provides facilities like standard input, standard output and standard
error streams. System class can’t be instantiated. 1. Java does not allow any
✓ Java Scanner is a utility class to read user input or process simple regex-based parsing of variable or function out of a
file or string source. Regex is a short form of regular expression. class.
Scanner Methods:
import java.util.Scanner; • nextBoolean() 2. main() method must be
• nextByte() within a class.
public class Program7 { • nextDouble()
public static void main(String[] args) { • nextFloat() 3. main() method must be
Scanner myObj = new Scanner(System.in); • nextInt()
• nextLine() public and static. Why?
JAVA Code
8
Structure vs. Class
Program8.c
#include <stdio.h>
C++ Code
double cgpa; karim.setName(iname);
public: //setter - getter
void setName(char *N){ strcpy(name, N);} cout << "Enter Rollno: ";
char *getName(){return name;} // cin >> karim.rollno; //Error – Why ?
void setRollno(int R){ rollno = R; } cin >> irollno;
int getRollno(){ return rollno;}; karim.setRollno(irollno);
void setCGPA(double CGPA){ cgpa = CGPA;}
double getCGPA(){ return cgpa;} cout << "Enter CGPA: ";
} Student; cin >> icgpa;
karim.setCGPA(icgpa);
Output:
Enter the name: Karim cout << karim.getName() << " ";
Enter Rollno: 12 cout << karim.getRollno();
Enter CGPA: 3.85 cout << " " << karim.getCGPA();
Karim 12 3.85 Does it allow a name as “Karim Ahmed”? Why? }
10
Structure vs. Class
❖ By default, all members of a structure are Public ❖ By default, all members of a class are Private
#include <iostream> #include <iostream>
#include <string.h> #include <string.h>
using namespace std; using namespace std;
C++ Code
int rollno; double cgpa;
double cgpa; public: //setter - getter
public: //setter - getter void setName(char *N){ strcpy(name, N);}
void setName(char *N){ strcpy(name, N);} char *getName(){return name;}
char *getName(){return name;} void setRollno(int R){ rollno = R; }
void setRollno(int R){ rollno = R; } int getRollno(){ return rollno;};
int getRollno(){ return rollno;}; void setCGPA(double CGPA){ cgpa = CGPA;}
void setCGPA(double CGPA){ cgpa = CGPA;} double getCGPA(){ return cgpa;}
double getCGPA(){ return cgpa;} };
} Student;
11
Use of Class in Java
public class StudentDemo{
❖ Java doesn’t support Structure, Pointer or Union. public static void main(String[] args){
❖ main method – static, public, inside class Student std = new Student();
String iname = new String();
import java.util.Scanner; StudentDemo.java Scanner obj = new Scanner(System.in);
int irollno;
class Student{
double icgpa;
private String name;
private int rollno;
System.out.print("Enter name: ");
private double cgpa;
iname = obj.nextLine();
std.setName(iname);
//setter - getter
Java Code
public void setName(String N){name = N;} System.out.print("Enter Rollno: ");
public String getName(){return name;}
irollno = obj.nextInt();
public void setRollno(int R){ rollno = R; }
std.setRollno(irollno);
public int getRollno(){ return rollno;};
public void setCGPA(double CGPA){ cgpa = CGPA;}
System.out.print("Enter CGPA: ");
public double getCGPA(){ return cgpa;} icgpa = obj.nextDouble();
}
std.setCGPA(icgpa);
Output: System.out.print("Name: " + std.getName()+
Enter name: Abdur Rahim " Rollno: " + std.getRollno() +
Enter Rollno: 12 " CGPA: " + std.getCGPA());
Enter CGPA: 3.85 }
Name: Abdur Rahim Rollno: 12 CGPA: 3.85 }
12
Features of OOP
Three Key Features of OOP
❖ Wrap up data and functions/methods together
Encapsulation ❖ Insulation of data from direct access by the program – data hiding
Java Code
myclass::myclass(){ MyClass ob = new MyClass();
data cout << "In constructor\n"; // System.out.println("a: "+a); Error - Why?
a = 10; System.out.println(ob.getA());
} }
C++ Code
}
int main(){
Interface myclass ob;
(Public method/data)
// cout << a; // wrong -Why?
Output:
cout << ob.geta(); // OK
In Constructor
return 0;
10
}
14
Polymorphism
One Interface, multiple methods
❖ Function overloading: (supported by both C++ & Java)
(1) Use a single name to multiple methods; Function / Constructor Overloading
(2) different number and types of arguments.
❖ Operator overloading: (Java doesn’t support customized operator overloading)
Use of single operator for different types of operands
C++ Code
int month, day, year; date sdate("31/12/99");
public: date idate(31, 12, 99);
date(char *str);
date(int d, int m, int y){ sdate.show();
day = d; idate.show();
month = m; return 0;
year = y; }
}
void show(){ Output:
cout << day << '/' << month << '/' ; 31/12/99
cout << year << '\n'; 31/12/99
}
15
};
Polymorphism
import java.time.LocalDate; PolymorphismDemo.java
class MyDate{
public class PolymorphismDemo {
private int day;
private int month; public static void main(String[] args) {
private int year; MyDate sDate = new MyDate("2024-05-12");
JAVA Code
MyDate iDate = new MyDate(23, 7, 2025);
MyDate(String str){
sDate.showMyDate();
LocalDate date = LocalDate.parse(str);
day = date.getDayOfMonth(); iDate.showMyDate();
month = date.getMonthValue(); }
year = date.getYear(); }
}
Output:
MyDate(int newDay, int newMonth, int newYear){ 12/5/2024
day = newDay; 23/7/2025
month = newMonth;
year = newYear;
} Operator overloading: Shall be discussed
a = 4 + 6; in next.
public void showMyDate(){
System.out.println(day+"/"+month+"/"+year); ob1 = ob2 + ob3; Not Supported in Java.
}
}
16
Inheritance
❖ One class inherits the properties of another class
Bird Superclass
❖ provide hierarchical classifications
Attributes
❖ Permits reuse of common code and data Feathers
#include <iostream> Lay eggs Subclass
using namespace std; Nonflying
Flying Bird
Bird
class base { Superclass Attributes Subclass Attributes
int x; … …
public:
void setx(int n) { x = n; } Robin Swallow Penguin Kiwi
void showx() { cout << x << '\n'; }
Attributes Attributes Attributes Attributes
int getx(){ return x; }
… … … …
};
int main(){
class derived: public base { Subclass derived ob;
int y;
public: ob.setx(10); Output:
C++ Code
void sety(int n) { y = n; } ob.sety(20); 10
void showy() { ob.showx(); 20
cout << y << '\n'; ob.showy(); 30
cout << y+getx() <<'\n'; return 0;
} }
};
17
Inheritance
class Base{ public class InheritanceDemo {
private int x; public static void main(String[] args) {
Derived obj = new Derived();
public void setX(int newX){ x = newX;}
public int getX(){ return x;} obj.setX(10);
public void showX(){System.out.println("X = "+x);} obj.setY(20);
} obj.showX();
obj.showY();
Java Code
class Derived extends Base{ }
private int y; }
public void setY(int newY){ y = newY;}
public void showY(){
System.out.println("Y= "+y + " X= "+ getX());
} Output:
} X = 10
Y= 20 X= 10
18
class Rectangle: public Figure{
Abstraction public:
Rectangle(double d1, double d2): Figure(d1, d2){}
double area(){
return dim1 * dim2; Function overriding, but
Abstract Class and Method: } not overloading. Why?
Abstract class is a superclass without a complete implementation };
of every method.
class Triangle: public Figure{
➢ There can be no objects of an abstract class.
public:
➢ Abstract can be used to create object references. Triangle(double d1, double d2): Figure(d1, d2){}
Abstract method refers to subclasser responsibility to override double area(){
it, otherwise, it will report a warning message. return dim1 * dim2 / 2;
➢ Constructor and static method cannot be Abstract. }
};
#include <iostream>
using namespace std; int main(){
Figure *p;
C++ Code
class Figure{ Rectangle r(10, 7);
protected: Triangle t(10, 5);
double dim1, dim2;
p = &r;
public: cout << "Rectangle Area: " << p->area() << endl;
Figure(double d1, double d2){
dim1 = d1; p = &t;
dim2 = d2; cout << "Triangle Area: " << p->area() << endl;
}
virtual double area() = 0; // Pure virtual function return 0;
}; }
19
Abstraction
abstract class Figure { public class Main {
double dim1, dim2; public static void main(String[] args) {
Figure(double a, double b){ dim1 = a; dim2 = b;} Rectangle r = new Rectangle(10,7);
abstract double area(); Triangle t = new Triangle(10, 5);
void show(){System.out.println("Abstract");} Figure figref;
Java Code
}
figref = r;
class Rectangle extends Figure { figref.show();
Rectangle(double a, double b) { super(a, b);}
double area(){ return dim1*dim2;} figref = t;
void show(){ figref.show();
System.out.println("Rectangle Area: "+area()); }
} }
}
int count = 0;
C++ Code
class X {
int main(void) { public:
int count = 0; static int count;
::count = 1; };
count = 2;
cout << "Global: " << ::count << endl; int X::count = 10;
cout << "Local: " << count;
return 0; int main () {
} cout << "count: " << X::count;
Output: }
Global: 1 Output:
Local: 2 count: 10 22
Namespaces in C++
A namespace is a declarative region that localizes the names of identifiers to avoid name collisions.
Three ways of using namespace.
#include <iostream> #include <iostream>
#include <string> #include <string> #include <iostream>
using std::cin; #include <string>
using namespace std;
C++ Code
int main(){ using std::cout;
std::string str; using std::endl;
using std::string; int main(){
std::cout << "Enter a string: "; string str;
getline(std::cin, str); int main(){
std::cout << str << std::endl; string str; cout << "Enter a string: ";
getline(cin, str);
return 0; cout << "Enter a string: "; cout << str << endl;
} getline(cin, str);
cout << str << endl; return 0;
Output: }
Enter a string: Love C++ return 0;
Love C++
}
Java programming uses separate namespace for each package.
23
Namespaces in C++
➢ C++ library is defined within its own namespace, std. ➢ There are two general form of using statement:
➢The general form of defining namespace is shown as: using namespace name;
namespace name{ using name::member;
namespace secondNS{
Output:
I: 99 cout << "X: " << secondNS::x << endl;
int x, y; cout << "Y: " << secondNS::y << endl;
Hello from firstNS!
}
10 9 8 7 6 5 4 3 2 1
X: 10 return 0;
Y: 20 }
25
Creation of Own Namespaces in C++
➢There can be more than one namespace declaration of the same name in the same file or
different files.
➢ Java is useless without much of the functionality in java.lang and so, it is implicitly
imported by the compiler for all programs.
➢ If a class with the same name exists in two different imported packages, then
compiler will remain silent and generate a compile-time error if the name is not used
explicitly with the class specifying its package.
➢ when a package is imported, only those items within the package declared as public
will be available to non-subclasses in the importing code.
➢ Packages act as containers for classes and other subordinate packages. Classes act as
containers for data and code.
28
Creation of Own Packages in Java
29
Creation of Own Packages in Java
package mypack;
Command line:
class Balance{
String name; java mypack.AccountBalance
double bal;
class AccountBalance {
public static void main(String[] args) {
Balance[] current = new Balance[3]; Output:
current[0] = new Balance(”Jerry", 123.23); Jerry: $123.23
current[1] = new Balance("Tell", 157.02); Tell: $157.02
current[2] = new Balance("Tom", -12.33); Tom: $-12.33
for(int i=0; i<3; i++) current[i].show();
}
}
30
Good Practices