Object oriented
programming
(through c++ and
Java)
Name - Sakshi Sharma
Batch- MCA (evening)
Roll no. -88
Submitted to- Ms. Indu
Ms. Samita
JAVA PROGRAMS
1.Class creation
package com.java;
class Rectangle{
int length , width;
void insert(int l,int w)
{
length=l;
width=w;
}
void calcuLateArea()
{
System.out.println("Area = "+ (length*width) );
}
}
public class RectangleArea
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,12);
r2.insert(4,5);
r1.calcuLateArea();
r2.calcuLateArea();
}
}
OUTPUT:
2.Inheritence
2(A). Single Inheritence
package com.java;
class Employees
{ void salary()
{
System.out.println("Salary = 200000");
}
}
class Programmer extends Employees
{ void bonus()
{
System.out.println("Bomus=50000");
}
}
public class SingleInheritence {
public static void main(String args[]){
Programmer p = new Programmer();
p.salary();
p.bonus();
}
}
OUTPUT:
2(B). Multilevel Inheritence
package com.java;
class box {
private double width, height, depth;
box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
class BoxWeight extends box
{
double weight;
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d);
weight =m;
}
}
class Shipment extends BoxWeight
{
double cost;
Shipment(double w, double h, double d, double m, double c) {
super(w, h, d, m);
cost = c;
}
}
public class MultilevelInheritence {
public static void main(String args[]){
Shipment ship1=new Shipment (1,2,3,5,7.6);
Shipment ship2 = new Shipment(2,3 ,6 ,10,1.28);
double vol;
vol=ship1.volume();
System.out.println("The volume of shipment 1 is "+vol);
System.out.println("The weight of shipment 1 is "+ship1.weight);
System.out.println("Shipping cost: Rs."+ship1.cost);
vol=ship2.volume();
System.out.println("The volume of shipment 2 is "+vol);
System.out.println("The weight of shipment 2 is "+ship2.weight);
System.out.println("Shipping cost: Rs."+ship2.cost);
}
}
OUTPUT:
2(C).Hirarcical Inheritence
package com.java;
class Employee {
double salary = 50000;
void displaySalary(){
System.out.println("Employee Salary:"+salary);
}
}
class FullTimeEmployee extends Employee{
double hike = 0.50;
void incrementSalary()
{
salary=salary+(salary*hike);
}
}
class InternEmployee extends Employee{
double hike = 0.25;
void incrementSalary(){
salary=salary+(salary*hike);
}
}
public class Hierarchicalinheritence {
public static void main(String[] args){
FullTimeEmployee emp1 = new FullTimeEmployee();
InternEmployee emp2 =new InternEmployee();
System.out.println("Salary of full time employee before incrementing:");
emp1.displaySalary();
System.out.println("Salary of an intern before incrementing:");
emp2.displaySalary();
emp1.incrementSalary();
emp2.incrementSalary();
System.out.println("Salary of full time employee after incrementing:" );
emp1.displaySalary();
System.out.println("Salary of an intern after incrementing:");
emp2.displaySalary();
}
}
OUTPUT:
3. Constructor
3(a). Default Constructor
package com.java;
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
}
//main method
public class constructor
{
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
OUTPUT:
3(b). Parameterised Constructor
package com.java;
class Student4
{
int id;
String name;
//creating a parameterized constructor
Student4(int i, String n) {
id = i;
name = n;
}
//method to display the values
void display() {
System.out.println(id + " " + name);
}
}
public class parameterised_constructor
{
public static void main(String args[])
{
//creating objects and passing values
Student4 s1 = new Student4(111, "Shaurya");
Student4 s2 = new Student4(222, "Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
OUTPUT:
3(C).Constructor Overloading
package com.java;
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
}
public class constructor_overloading{
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
OUTPUT:
4.Thread Creation
package com.java;
import java.io.*;
class create extends Thread{
public void run(){
System.out.println("Creating a thread in java");
}
}
public class thread_creation {
public static void main(String[] args){
create g =new create();
g.start();
}
}
OUTPUT:
5. Multithreading
package com.java;
import java.lang.Thread;
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Thread A" +i);
}
System.out.println("End of Thread A");
}
}
class B extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Thread B" +i);
}
System.out.println("End of Thread B");
}
}
class C extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Thread C" +i);
}
System.out.println("End of Thread C");
}
}
public class multithreading {
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
OUTPUT:
6.Applet
// A Hello World Applet
// Save file as HelloWorld.java
import java.applet.Applet;
import java.awt.Graphics;
// HelloWorld class extends Applet
public class HelloWorld extends Applet
{
// Overriding paint() method
@Override
public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}
}
OUTPUT:
7. Java Exception Handling
7(a).try…catch block
class Main {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
OUTPUT:
7(B).Finally block
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
OUTPUT:
7(C).Java throw
class Main {
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}
OUTPUT:
Throws Keyword:
import java.io.*;
class Main {
// declareing the type of exception
public static void findFile() throws IOException {
// code that may generate IOException
File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
}
public static void main(String[] args) {
try {
findFile();
}
catch (IOException e) {
System.out.println(e);
}
}
}
OUTPUT:
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
8.Creating Package
// Name of package to be created
package data;
// Class to which the above package belongs
public class Demo {
// Member functions of the class- 'Demo'
// Method 1 - To show()
public void show()
{
// Print message
System.out.println("Hi Everyone");
}
// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}
Importing a Package :
import data.*;
// Class to which the package belongs
class ncj {
// main driver method
public static void main(String arg[])
{
// Creating an object of Demo class
Demo d = new Demo();
// Calling the functions show() and view()
// using the object of Demo class
d.show();
d.view();
}
}
OUTPUT:
C++ PROGRAMS
CONSTRUCTORS
1.PARAMETERIZED CONSTRUCTORS
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len) {
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
// Main function for the program
int main() {
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
OUTPUT:
2.COPY CONSTRUCTORS
#include<iostream>
using namespace std;
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
num1 = n1;
num2 = n2;
}
Demo(const Demo &n) {
num1 = n.num1;
num2 = n.num2;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main() {
Demo obj1(10, 20);
Demo obj2 = obj1;
obj1.display();
obj2.display();
return 0;
}
OUTPUT:
3.OVERLOADED CONSTRUCTORS
#include <iostream>
using namespace std;
class Person {
private:
int age;
public:
// 1. Constructor with no arguments
Person() {
age = 20;
}
// 2. Constructor with an argument
Person(int a) {
age = a;
}
int getAge() {
return age;
}
};
int main() {
Person person1, person2(45);
cout << "Person1 Age = " << person1.getAge() << endl;
cout << "Person2 Age = " << person2.getAge() << endl;
return 0;
}
OUTPUT:
4. DYNAMIC CONSTRUCTORS
#include <iostream>
using namespace std;
class pink {
const char* p;
public:
// default constructor
pink()
{
// allocating memory at run time
p = new char[6];
p = "pink";
}
void display()
{
cout << p << endl;
}
};
int main()
{
pink obj;
obj.display();
}
OUTPUT:
IMPLEMENTATION OF DESTRUCTORS
#include<iostream>
using namespace std;
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
cout<<"Inside Constructor"<<endl;
num1 = n1;
num2 = n2;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
~Demo() {
cout<<"Inside Destructor";
}
};
int main() {
Demo obj1(10, 20);
obj1.display();
return 0;
}
OUTPUT:
INHERITANCE
1. SINGLE INHERITANCE
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking...";
}
};
int main(void) {
Dog d1;
d1.eat();
d1.bark();
return 0;
}
OUTPUT:
2. MULTILEVEL INHERITANCE
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
OUTPUT:
3. MULTIPLE INHERITANCE
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};
class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl;
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();
return 0;
}
OUTPUT:
4. HYBRID INHERITANCE
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
};
class D : public B, public C
{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
}
};
int main()
{
D d;
d.mul();
return 0;
}
OUTPUT:
5. HIERARCHICAL INHERITANCE
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}
OUTPUT:
6. FUNCTION OVERLOADING WITH DIFFERENT
TYPES OF ARGUMENTS
#include<iostream>
using namespace std;
int mul(int,int);
float mul(float,int);
int mul(int a,int b)
{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0;
}
OUTPUT:
7. FUNCTION WITH PASS BY REFERENCE
#include <stdio.h>
void swapnum(int &i, int &j) {
int temp = i;
i = j;
j = temp;
}
int main(void) {
int a = 10;
int b = 20;
swapnum(a, b);
printf("A is %d and B is %d\n", a, b);
return 0;
}
OUTPUT:
8. PASS BY VALUE
#include <iostream>
#include<vector>
using namespace std;
//Function prototyping as defined after it is being called
int sumOf(int, int);
int main()
{
//variable declaration
int num1, num2, addition=0;
cout << "Enter the two numbers you want to add : \n\n";
cin >> num1;
cin >> num2;
/*
Demonstrating Multi-line Commenting:
Passing the values stored in the variables num1 and num2 as parameter to function
sumOf().
The value returned by the function is stored in the variable output
*/
addition = sumOf(num1, num2);
cout << "\n\nThe Sum of the two numbers " << num1 << " and " << num2 << ",
returned by the function sumOf(), is = " << addition;
cout << "\n\n\n";
return 0;
}
// Defining the function sumOf(a,b) which is called by Passing Values and returns the sum
of a and b
int sumOf(int n1, int n2)
{
int sum;
//Computing the addition of the two values the function is called with
sum = n1 + n2;
//Returning the addition to the point where this function is called from
return sum;
}
OUTPUT:
9. OPERATOR OVERLOADING
PROGRAM TO OVERLOAD THE UNARY OPERATOR
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
OUTPUT:
10. PROGRAM TO OVERLOAD THE BINARY OPERATORS
#include <iostream>
using namespace std;
class A
{
int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};
void A :: operator+(A a)
{
int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;
}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
OUTPUT:
11. METHOD OVERRIDING
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
OUTPUT:
12. EXCEPTION HANDLING
#include <iostream>
using namespace std;
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
OUTPUT:
13. ABSTRACT CLASS AND PURE VIRTUAL FUNCTION
#include <iostream>
using namespace std;
// Abstract class
class Shape {
protected:
float dimension;
public:
void getDimension() {
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0;
};
// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};
int main() {
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;
}
OUTPUT: