0% found this document useful (0 votes)
216 views

CS2312 Oop

The document discusses several C++ programs that demonstrate object oriented programming concepts like inheritance, polymorphism, operator overloading, and dynamic memory allocation. The first program implements bank account details using inheritance - a base Bank class is defined, with derived Savings and Current subclasses. Member functions are defined to get deposit/withdrawal details and update balances for each account type. The second program overloads operators like +, -, *, / for a Complex number class using friend functions. Arithmetic operations are performed on complex number objects and results are displayed. The last program implements a matrix class with dynamic memory allocation for rows and columns. Member functions are used to get/display matrix elements. Copy constructor and assignment operators are overloaded

Uploaded by

vanckam
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
216 views

CS2312 Oop

The document discusses several C++ programs that demonstrate object oriented programming concepts like inheritance, polymorphism, operator overloading, and dynamic memory allocation. The first program implements bank account details using inheritance - a base Bank class is defined, with derived Savings and Current subclasses. Member functions are defined to get deposit/withdrawal details and update balances for each account type. The second program overloads operators like +, -, *, / for a Complex number class using friend functions. Arithmetic operations are performed on complex number objects and results are displayed. The last program implements a matrix class with dynamic memory allocation for rows and columns. Member functions are used to get/display matrix elements. Copy constructor and assignment operators are overloaded

Uploaded by

vanckam
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 57

FUNCTION OVERLOADING AIM: To write a C++ program to perform function overloading. ALGORITHM: Step1: Start the program.

Step2: Define a class with necessary data items and member function with same function name and different number and types of arguments. Step3: Define a member function to calculate the volume of different shapes. Step4: Define the main function. Step5: Call the member function using the object created. Step6: Print the result. Step7: Stop the program. PROGRAM: #include<iostream.h> #include<conio.h> class overloading { private: int s,r,l,b,h; public: int volume(int s) { return(s*s*s); } long volume(int l,int b,int h) { return(l*b*h); }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

float volume(int r,int h) { return(3.14*r*h); } }; void main() { clrscr(); overloading o; cout<<"Output is"<<endl; cout<<"Volume ="<<o.volume(10); cout<<"\nVolume="<<o.volume(2,8); cout<<"\nVolume="<<o.volume(7,75,15); getch(); } OUTPUT: Output is Volume=1000 Volume=50.240002 Volume=7875

CS2312-OBJECT ORIENTED PROGRAMMING LAB

FUNCTION OVERLOADING WITH DEFAULT ARGUMENT AIM: To write a C++program to perform function overloading with default argument ALGORITHM: Step1: Start the program. Step2: Declare a function printline which takes a character and integer as argument. Step3:Set a loop using variable i and initialize it to zero. Check if i<count, if true print the characters and increment the count value, else terminate the process. Step4: Print the result. Step5: Stop the program. PROGRAM: #include<iostream.h> #include<conio.h> void printline(char='_',int=7); void main() { clrscr(); printline(); printline('!'); printline('*',4); printline('r',5); getch(); } void printline(char ch,int count) {

CS2312-OBJECT ORIENTED PROGRAMMING LAB

int i; cout<<endl; for(i=0;i<count;i++) cout<<ch; } OUTPUT: _______ !!!!!!! **** rrrrr

CS2312-OBJECT ORIENTED PROGRAMMING LAB

SIMPLE CLASS DESIGN IN C++, NAMESPACE, OBJECT CREATION AIM: To write a C++ program to design a simple class. ALGORITHM: Step1: Start the program. Step2: Define a class with necessary data items and member function. Step3: Define the main function. Step4: Create an object for the class and call the member functions using that object. Step5: Print the result. Step6: Stop the program. PROGRAM: #include<iostream> using namespace std; class arithmetic { private: int a,b,c; float d; public: void input() { cout<<"Enter 2 Numbers:"; cin>>a>>b; } void manipulate() { c=a+b;

CS2312-OBJECT ORIENTED PROGRAMMING LAB

d=(float)c/3; } void display() { cout<<"\nC="<<c; cout<<"\nD="<<d; } }; void main() { clrscr(); arithmetic a; a.input(); a.manipulate(); a.display(); getch(); } OUTPUT: Enter 2 Numbers: 5 10 C=15 D=5.0

CS2312-OBJECT ORIENTED PROGRAMMING LAB

CLASS DESIGN IN C++ USING DYNAMIC MEMORY ALLOCATION, DESTRUCTOR, COPY CONSTRUCTOR AIM: To write a C++ program to print matrix with dynamic memory allocation, copy constructor, destructor and operator overloading. ALGORITHM: Step1: Start the program . Step2: The matrix class is declared. Step3: In the main function the size of matrix is declared and the values are entered. Step4: Using copy constructor values are accessed and memory is allocated dynamically for rows and columns and matrix is displayed. Step5: The assignment operator is overloaded and the matrix is printed. Step6: The dynamically allocated memory can be deallocated with the help of destructor. Step6: Stop the program. PROGRAM: #include<iostream.h> #include<conio.h> class matrix { int **m; int row,col; public: matrix() {

CS2312-OBJECT ORIENTED PROGRAMMING LAB

row=col=0; m=NULL; } matrix(int r,int c); ~matrix(); void getmatrix(); void showmatrix(); matrix(matrix &m2); matrix& operator=(matrix &m2); }; matrix::~matrix() { for(int i=0;i<row;i++) delete m[i]; delete m; } matrix::matrix(int r,int c) { row=r; col=c; m=new int*[row]; for(int i=0;i<row;i++) m[i]=new int[col]; } matrix::matrix(matrix &m2) { cout<<"\n Copy Constructor invoked.\n"; row=m2.row; col=m2.col; m=new int*[row]; for(int i=0;i<row;i++) m[i]=new int[col]; for(i=0;i<row;i++) for(int j=0;j<row;j++) m[i][j]=m2.m[i][j]; } matrix& matrix::operator=(matrix &m2) { cout<<"\n Assignment Operator Overloading.\n";

CS2312-OBJECT ORIENTED PROGRAMMING LAB

row=m2.row; col=m2.col; m=new int*[row]; for(int i=0;i<row;i++) m[i]=new int[col]; for( i=0;i<row;i++) for(int j=0;j<row;j++) m[i][j]=m2.m[i][j]; return *this; } void matrix::getmatrix() { for(int i=0;i<row;i++) for(int j=0;j<col;j++) cin>>m[i][j]; } void matrix::showmatrix() { for(int i=0;i<row;i++) { for(int j=0;j<col;j++) cout<<"\t"<<m[i][j]; cout<<"\n"; } } void main() { int r,c; clrscr(); cout<<"\n Enter rows and cols of the matrix.\n"; cin>>r>>c; matrix m1(r,c); cout<<"\n Enter the matrix elements one by one.\n"; m1.getmatrix(); cout<<"\n Entered matrix is.\n"; m1.showmatrix(); matrix m2=m1; cout<<"\nResult of copy constructor is.\n"; m2.showmatrix();

CS2312-OBJECT ORIENTED PROGRAMMING LAB

matrix m3; m3=m1; cout<<"\n Result of assignment operator overloading.\n"; m3.showmatrix(); getch(); }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

OUTPUT: Enter the rows and cols of the matrix. 3 3 Enter the matrix elements one by one. 1 2 3 4 5 6 7 8 9 Entered matrix is. 1 4 7 2 5 8 3 6 9

Copy Constructor invoked. Result of copy constructor is. 1 4 7 2 5 8 3 6 9

Assignment Operator overloading. Result of assignment operator overloading. 1 4 2 5 3 6

CS2312-OBJECT ORIENTED PROGRAMMING LAB

9 OPERATOR OVERLOADING USING FRIEND FUNCTION

AIM: To write a C++ program to import operator overloading with friend function concept. ALGORITHM: Step1: Start the program. Step2: Create a class complex with 3 constructor to perform constructor overloading. The first constructor takes no argument which is used to create objects which are not initialized. Step3: The second takes one argument which is used to create object and initialize them to specific value. Step4: Overload the arithmetic operators using friend function to perform arithmetic operation on the complex number. Step 5: Stop the program PROGRAM: #include<iostream.h> #include<conio.h> #include<math.h> class complex { float x,y; public: complex(){} complex(float z) { x=y=z; } complex(float real,float img)

CS2312-OBJECT ORIENTED PROGRAMMING LAB

{ x=real; y=img; } friend complex operator+(complex,complex); friend complex operator-(complex,complex); friend complex operator*(complex,complex); friend complex operator/(complex,complex); friend void show(complex); }; complex operator+(complex c1,complex c2) { complex c3; c3.x=c1.x+c2.x; c3.y=c1.y+c2.y; return c3; } complex operator-(complex c1,complex c2) { complex c3; c3.x=c1.x-c2.x; c3.y=c1.y-c2.y; return c3; } complex operator*(complex c1,complex c2) { complex c3; c3.x=(c1.x*c2.x)-(c1.y*c2.y); c3.y=(c1.y*c2.x)+(c1.x*c2.y); return c3; } complex operator/(complex c1,complex c2) { complex c3; float a; a=((c2.x*c2.x)+(c2.y*c2.y)); c3.x=((c1.x*c2.x)+(c1.y*c2.y))/a; c3.y=((c1.y*c2.x)-(c1.x*c2.y))/a; return c3;

CS2312-OBJECT ORIENTED PROGRAMMING LAB

} void show(complex c) { if(c.y<0) cout<<c.x<<"-j"<<fabs(c.y)<<endl; else cout<<c.x<<"+j"<<fabs(c.y)<<endl; } void main() { complex A(1,2); complex B(3,1); complex C,D,E,F; clrscr(); C=A+B; D=A-B; E=A*B; F=A/B; cout<<"Complex No:1="; show(A); cout<<"Complex No:2="; show(B); cout<<"Sum ="; show(C); cout<<"Difference="; show(D); cout<<"Product="; show(E); cout<<"Quotient="; show(F); getch(); } OUTPUT: Complex No:1=1+j2; Complex No:2=3+j1; Sum=4+j3; Difference=-2+j1;

CS2312-OBJECT ORIENTED PROGRAMMING LAB

Product=1+7j; Quotient=0.5+0.5j OVERLOADING ASSIGNMENT OPERATOR, TYPE CONVERSION AIM: To write a C++ program to implement necessary operator overloading and type conversion. ALGORITHM: Step1: Start the program. Step2: Invoke the parameterized constructor complex for x, y, z values. Step 3: Create object for complex class. Step 4: Copy the values from x to u using complex u(x) function. Step 5: Again copy the values from x to v using complex v=x. Step 6: Again copy the values from x to w and to a. Step 7: Print the real and imaginary values. Step 8: Stop the program. PROGRAM: #include<iostream.h> #include<conio.h> #include<math.h> class complex { double real,imag; public: complex(double re=0.0,double imag=0.0) { real=re; imag=imag; } complex(const complex& othercomplex) { real=othercomplex.real; imag=othercomplex.imag; } operator double() const

CS2312-OBJECT ORIENTED PROGRAMMING LAB

{ return real; } complex& operator=(const complex&); friend complex operator+(const complex&,const complex&); friend complex operator-(const complex&,const complex&); }; complex& complex::operator=(const complex& rhs) { real=rhs.real; imag=rhs.imag; return *this; } complex operator+(const complex& lhs,const complex& rhs) { return complex(lhs.real+rhs.real,lhs.imag+rhs.imag); } complex operator-(const complex& lhs,const complex& rhs) { return complex(lhs.real-rhs.real,lhs.imag-rhs.imag); } void main() { clrscr(); complex a; complex x(1.0,2.0),y(20.0),z(11.0,12.0); complex u(x); complex v=x; complex w=x+y-z; a=x+y-z; cout<<"The real part of complex number: "<<double(a)<<endl; cout<<"The imaginary part of complex number: "<<exp(a)<<endl; getch(); } OUTPUT: The real part of complex number: 10

CS2312-OBJECT ORIENTED PROGRAMMING LAB

The imag part of complex number: 220226.465795 INHERITANCE AIM: To write a C++ program to implement bank details using inheritance concept. ALGORITHM: Step1: Start the program. Step2: Create a bank class. Step3: Create a subclass savings which inherits properties from the bank class and current class that inherits from savings class. Step4: The savings class defines member function to get details about the deposit and withdrawal amount and update balance information for current account. Step5: Write a member function to get deposit amount and to update balance information for current account. Step6: Write a member function to display the balance information for saving account. Step7: Write a member function to display the balance information for respective account type. Step8: Stop the program. PROGRAM: #include<iostream.h> #include<conio.h> class bank { public: char *cname; long int accno;

CS2312-OBJECT ORIENTED PROGRAMMING LAB

void display() { cout<<cname; cout<<accno; } }; class savings: public bank { public: long double wdraw,dep,bal; void saves() { cout<<"Enter the amount to be deposited=Rs."; cin>>dep; bal+=dep; cout<<"\nEnter the amount to be withdrawn=Rs."; cin>>wdraw; bal-=wdraw; cout<<"\nYour account balance is=Rs."<<bal; } }; class current :public savings { public: void info() { cout<<"Last amount withdrawn=Rs."<<wdraw<<endl; cout<<"Last amount deposited=Rs."<<dep<<endl; cout<<"Your account balance is=Rs."<<bal<<endl; } }; void main() { int ch; current a; clrscr(); cout<<"Enter customer name: "; cin>>a.cname; cout<<"\n Enter your A/c no.:";

CS2312-OBJECT ORIENTED PROGRAMMING LAB

cin>>a.accno; cout<<endl; while(1) { cout<<"Enter the A/c type: 1.Savings 2.Current 3.Exit\n"; cin>>ch; switch(ch) { case 1: a.saves(); break; case 2: a.info(); break; case 3: break; default: cout<<"Invalid choice"; break; } if(ch==3) break; } getch(); } OUTPUT: Enter customer name:xxx Enter your A/c no.:566 Enter the A/c type:1.Savings 2.Current 3.Exit 1 Enter the amount to be deposited=Rs.5000 Enter the amount to be withdrawn=Rs.500 Your A/c balance is=Rs.4500 Enter the A/c type:1.Savings 2.Current 3.Exit 2 Last amount withdrawn=Rs.500 Last amount deposited=Rs.5000 Your account balance is=Rs.4500

CS2312-OBJECT ORIENTED PROGRAMMING LAB

Enter the A/c type:1.Savings 2.Current 3.Exit 3 RUNTIME POLYMORPHISM USING VITUAL FUNCTION AIM: To write a C++ program to calculate the area of triangle and rectangle using derived classes and display the result using virtual function. ALGORITHM: Step1: Start the program. Step2: Create a base class shape. Step3: Derive two subclasses triangle and rectangle from the base class shape. Step4: Derive member function get_data() and display_area(). Step5: Find out the area of triangle and rectangle and display the result using display_area(). Step6: Make display_area() as a virtual function. Step7: Print the result. Step8: Stop the program. PROGRAM: #include<iostream.h> #include<conio.h> class shape { public: virtual void getdata(){} virtual void display(){} }; class triangle: public shape { int h,bs; float at;

CS2312-OBJECT ORIENTED PROGRAMMING LAB

public: void getdata() { cout<<"Enter the height and base of triangle = "; cin>>h>>bs; } areatri() { at=((bs*h)/2.0); return(at); } void display() { cout<<"Area of triangle= "<<at<<"sq.units"<<endl; } }; class rectangle: public shape { int l,b,ar; public: void getdata() { cout<<"Enter the lengthvand breadth of rectangle = "; cin>>l>>b; } arearec() { ar=l*b; return(ar); } void display() { cout<<"Area of rectangle= "<<ar<<"sq.units"<<endl; } }; void main() { clrscr();

CS2312-OBJECT ORIENTED PROGRAMMING LAB

shape s; triangle t; rectangle r; shape *bptr; cout<<"Triangle:"<<endl; bptr=&t; bptr->getdata(); t.areatri(); bptr->display(); cout<<"Rectangle: "<<endl; bptr=&r; bptr->getdata(); r.arearec(); bptr->display(); getch(); } OUTPUT: Triangle Enter the height and base of triangle = 4 6 Area of triangle=12 sq.units Rectangle Enter the length and breadth of rectangle = 7 8 Area of rectangle=56 sq.units

CS2312-OBJECT ORIENTED PROGRAMMING LAB

TEMPLATE DESIGN IN C++ AIM: To write a C++ program to print the Student Details. ALGORITHM: Step1: Start the program. Step2: Assign a variable n and a character name[20]. Step3: Read the number of students value n. Step4: Use for loop and get the student details. Step5: Print the details. Step6: Stop the program. PROGRAM: #include<iostream.h> #include<conio.h> template <class t> get(t a) { cout<<"\nEnter the details of student\t"<<a; t no,m1,m2,m3,avg,tot; cout<<"\nEnter the no."; cin>>no; cout<<"\nEnter marks in three subjects"; cin>>m1>>m2>>m3; tot=m1+m2+m3; avg=tot/3; cout<<"\nResult of No."<<no; cout<<"\nm1="<<m1<<"\tm2="<<m2<<"\tm3="<<m3; cout<<"\ntotal\t"<<tot; cout<<"\navg\t"<<avg; } void main() {

CS2312-OBJECT ORIENTED PROGRAMMING LAB

clrscr(); int n; char name[20]; cout<<"Enter the no of students to get:\t"; cin>>n; for(int i=1;i<=n;i++) { cout<<"\nEnter the student name:\t"; cin>>name; get(i); cout<<"\nName"<<name; } getch(); } OUTPUT: Enter the no of students to get 2 Enter the student name : Raj Enter the details of student 1 Enter the no.20 Enter the marks in three subjects Result of No. 20 m1=90 m2=80 total 270 avg 90 Name Raj m3=100

90

80

100

Enter the no of students to get 2 Enter the student name : Suji Enter the details of student 1 Enter the no.20 Enter the marks in three subjects 100 Result of No. 20 m1=100 m2=100 total 270 avg 90 Name Suji m3=70

100

70

CS2312-OBJECT ORIENTED PROGRAMMING LAB

HANDLING I/O AIM: To write a C++ program to find the square root of a number and to format the display. ALGORITHM: Step1: Start the program. Step2: cout.width( ) specifies the required field size for displaying the output. Step3: cout.precision( ) specifies the number of digits to be displayed after the decimal point of a floating point number. Step4: cout. fill( ) specifies a character to be filled is unused portion of the field. Step5: cout.setf(ios::left,ios::adjustfield) Left justification output. Step6: cout.setf(ios::right,ios::adjustfield) Right justification output. Step7: cout.setf(ios::showpoint) shows trailing decimal point and zeros. Step8: cout.setf(ios::showpos) prints + before positive integers. Step 9: cout.setf(ios::fixed,ios::float field) use ordinary floating point notation. Step10: cout.setf(ios::scientific,ios::float field) use exponential floating point notation. Step11: cout.setf(ios::internal,ios::float field) paddding occurs between sign/base indicator and the number, when the number output failsto fill the full widthof the field. Step12: Print the result. Step 13: Stop the program.

CS2312-OBJECT ORIENTED PROGRAMMING LAB

PROGRAM: #include<iostream.h> #include<conio.h> #include<math.h> void main() { int i; clrscr(); cout.fill('*'); cout.setf(ios::left,ios::adjustfield); cout.width(10); cout<<"VALUE="; cout.setf(ios::right,ios::adjustfield); cout.width(15); cout<<"SQUARE ROOT OF\n"; cout.fill('.'); cout.precision(4); cout.setf(ios::showpoint); cout.setf(ios::showpos); cout.setf(ios::fixed,ios::floatfield); for(i=1;i<=10;i++) { cout.setf(ios::internal,ios::adjustfield); cout.width(5); cout<<i; cout.setf(ios::right,ios::adjustfield); cout.width(20); cout<<sqrt(i)<<"\n"; } cout.setf(ios::scientific,ios::floatfield); cout<<"\nSQRT(100)="<<sqrt(100)<<"\n"; getch(); }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

OUTPUT: VALUE=****SQUARE ROOT OF +1+1.0000 +2+1.4142 +3+1.7321 +4+2.0000 +5+2.2361 +6+2.4495 +7+2.6458 +8+2.8284 +9+3.0000 +..10+3.1623 SQRT(100)=+1.0000e+01

CS2312-OBJECT ORIENTED PROGRAMMING LAB

HANDLING TRY THROW CATCH AIM: To write a C++ program to validate array references using Exception Handling. ALGORITHM: Step1: Start the program. Step2: Define the maximum array size. Step3: Display succeeded if an element is updated within the array limit. Step4: If an element is updated beyond the array limit an exception is generated. Step5: Catch block issues a warning message on the output generated if exception thrown. PROGRAM: #include<iostream.h> const int ARR_SIZE=10; class array { private: int arr[ARR_SIZE]; public: class RANGE{}; int &operator[](int i) { if(i<0||i>=ARR_SIZE) throw RANGE(); return arr[i];

CS2312-OBJECT ORIENTED PROGRAMMING LAB

} }; void main() { array a; cout<<Maximum array size allowed=<<ARR_SIZE<<endl; try { cout<<\n Trying to refer a[1]=; a[1]=10; cout<<succeeded; cout<<\n Trying to refer a[15]; a[15]=10; cout<<succeeded ; } catch (array::RANGE) { cout<<cout of range in array reference; } } OUTPUT: Maximum array size allowed=10 Trying to refer a[1]=Succeeded Trying to refer a[15]=Out of range in array reference

CS2312-OBJECT ORIENTED PROGRAMMING LAB

PROGRAM DEVELOPMENT USING STL AIM: To write a C++ program to declare a list and to perform some operations using STL. ALGORITHM: Step1: Create an empty list lst to hold integers. Step2: Get the number of elements to insert in the list. Step3: Using push_back() insert the elements in the list. Step4: Access the contents of the list by declaring and initializing iterator. Step5: Using sort() function sort the list. Step6: Display the sorted list. Step7: Modify the elements of the list by adding 1000 to each element. Step8: Display the modified list. PROGRAM: #include<iostream.h> #include<list.h> void main() { list<int>lst; int i,n,item; cout<<\n How many elements you want to insert?<<endl; cin>>n; cout<<\nEnter the elements in the list<<endl; for(i=0;i<n;i++) { cin>>item; lst.push_back(item); }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

cout<<The size of the list is= <<lst.size()<<endl; cout<<The contents of the list are: <<endl; list<int>::iterator ptr=lst.begin() while(ptr!=lst.end()) { cout<<*ptr<< ; ptr++; } lst.sort(); cout<<\nSorted elements of the list are:<<endl; ptr=lst.begin(); while(ptr!=lst.end()) { cout<<*ptr<< ; ptr++; } ptr=lst.begin(); while(ptr!=lst.end()) { *ptr=*ptr+1000; ptr++; } cout<<\nModified elements of the list are:<<endl; ptr=lst.begin(); while(ptr!=lst.end()) { cout<<*ptr<< ; ptr++; } cout<<\n\n; }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

OUTPUT: How many elements you want to insert? 5 Enter the elements of the list 30 10 40 50 20 The size of the list is=5 The contents of the list are: 30 10 40 50 20 Sorted elements of the list are: 10 20 30 40 50 Modified elements of the list are: 1010 1020 1030 1040 1050

CS2312-OBJECT ORIENTED PROGRAMMING LAB

SIMPLE CLASS DESIGN IN JAVA AIM: To write a program depicting simple class design using JAVA. ALGORITHM: Step1: Start the program. Step2: Define main method inside the class specification. Step3: Define three string variables. Step4: Display the length of the strings. Step5: Display the character of index three of first string. Step6: Compare all Strings and print the result. Step7: Stop the program. PROGRAM: class basic { public static void main(String args[]) { String strob1="Sriram"; String strob2="ram"; String strob3=strob1; System.out.println("lengthof String1="+strob1.length()); System.out.println("lengthof String2="+strob2.length()); System.out.println("character at 3rd position="+strob1.charAt(3)); if(strob1.equals(strob2)) System.out.println("s1=s2"); if(strob1.equals(strob3)) System.out.println("s1=s3"); else System.out.println("s1!=s3"); } }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

SIMPLE CLASS DESIGN IN JAVA AIM: To write a program for simple class design using JAVA. ALGORITHM: Step1: Start the program. Step2: Define main method inside the class specification. Step3:Define method getdata() to get width, height and depth. Step4:Display the volume. Step5:Stop the program. PROGRAM: class room { float width,height,depth; void getdata(float a, float b, float c) { width=a; height=b; depth=c; } } class boxdemo { public static void main(String args[]) { double volume; room room1=new room(); room1.getdata(10,20,15); volume=room1.width*room1.height*room1.depth; System.out.println("volume="+volume); }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

} OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

DESIGNING PACKAGES AIM: To write a program to create packages using JAVA. ALGORITHM: Step1: Create a directory named as pack. Step2: Open file Name.java and Roll.java inside pack. Step3: Inside pack directory create a subdirectory named subpack. Step4: Inside subpack create file named Address.java. Step5: In the root directory create a main application packdemo.java which imports Address class of subpack file. Step6:Get the Name, Roll and Address and display them. PROGRAM: Name.java: package pack; class Name { String n; String setname(String name) { n=name; return n; } } Roll.java package pack;

CS2312-OBJECT ORIENTED PROGRAMMING LAB

public class Roll { protected int roll; protected int getroll(int r) { roll=r; Name n1=new Name(); System.out.println("Name: "+n1.setname("jj")); return roll; } } Address.java package pack.subpack; import pack.Roll; public class Address extends Roll { public String address; public String getaddress(String a) { address=a; Address a1=new Address(); System.out.println("Roll no:"+a1.getroll(7)); return address; } } packdemo.java import pack.subpack.Address; public class packdemo { public static void main(String args[]) { Address a1=new Address(); System.out.println("address is "+a1.getaddress("mgm,chennai")); } }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

DESIGNING INTERFACES AIM: To write a java program to implement interface and to generate random numbers using an interface. ALGORITHM: Step1: Start the program. Step2: Define an interface for stack. Step3: Define a class with data members and member function that implements a stack interfaces. Step4: Define main method. Step5: Call method push to insert the elements. Step6: Pop all the elements from stack. Step7: Stop the program. PROGRAM: interface IntStack { void push(int item); int pop(); } class FixedStack implements IntStack { private int stck[]; private int sp; FixedStack(int size) { stck=new int[size]; sp=-1; }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

public void push(int item) { if(sp==stck.length-1) System.out.println("stack is full"); else stck[++sp]=item; } public int pop() { if(sp<0) { System.out.println("stack is empty"); return 0; } else return stck[sp--]; } } class testing { public static void main(String args[]) { FixedStack mystack=new FixedStack(5); for(int i=0;i<5;i++) mystack.push(i); System.out.println("contents"); for(int i=0;i<5;i++) System.out.println(mystack.pop()); } }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

EXTENDING INTERFACES USING INHERITANCE AIM: To write a JAVA program to extend an interface. ALGORITHM: Step1: Start the program. Step2: Define two interfaces A and B, where B inherits the properties of A. Step3: Define a class that implements interface B and define all members inside class specification. Step4: Define main method. Step5: Create an object and invoke all methods. Step6: Stop the Program. PROGRAM: interface A { void meth1(); void meth2(); } interface B extends A { void meth3(); }; class myclass implements B { public void meth1() { System.out.println("Implements meth1()"); } public void meth2() { System.out.println("Implements meth2()"); }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

public void meth3() { System.out.println("Implements meth3()"); } } class IFExtend { public static void main(String args[]) { myclass ob=new myclass(); ob.meth1(); ob.meth2(); ob.meth3(); } } OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

EXCEPTION HANDLING AIM: To write a JAVA program to handle predefined exception. ALGORITHM: Step1: Start Step2: Enclose the code(division by zero) inside a try block. Step3: Following the try block place a catch block that handles the exception. Step4: Try and catch processes arithmetic operation exception divide by zero. Step5: Stop the process. PROGRAM: class eee { public static void main(String args[]) { int d,a; try { d=0; a=42/d; System.out.println("Divide by zero error"); } catch(ArithmeticException e) { System.out.println("Exception caught"); } System.out.println("Divide fails"); } }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

CREATING USER DEFINED EXCEPTION AIM: To write a java program to handle User Defined Exception. ALGORITHM: Step1: Start the program. Step2: Define a new subclass called myexception which inherits the properties of class Exception. Step3: Use the subclass to signal an error condition in amethod. Step4: Define the constructor and a method to describe the User Defined Exception inside class specification. Step5: Define the main method. Step6: Try and catch processes the exception. Step7: Stop the program. PROGRAM: class myException extends Exception { private int detail; myException(int a) { detail=a; } public String tostring() { return("myexception["+detail+"]"); } }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

class mom { static void compute(int a)throws myException { System.out.println("Called compute("+a+")"); if(a>10) throw new myException(a); System.out.println("normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch(myException e) { System.out.println("caught"+e); } } } OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

HANDLING INPUT OUTPUT AIM: To write a java program to read characters from the console until user exists. ALGORITHM: Step1: Start the program. Step2: Read(), reads a character from input stream and returns it as an integer value. Step3: It returns -1, when an end of stream is reached it throws IOException. Step4: Stop the program. PROGRAM: import java.io.*; class BRread { public static void main(String args[])throws IOException { char c; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the charcteristics 'q'to quit"); do { c=(char)br.read(); System.out.println(c); } while(c!='q'); } }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

DESIGNING MULTIPLE THREADS AIM: To write a java program to create multiple threads. ALGORITHM: Step1:Start the program. Step2: Create a class that implements Runnable interface. Step3: Create Multiple threads by installing object type method Step4: Define amethod called run() that constitutes the new thread. Step5: After creation of a new thread, start methods invokes run method. Step6: Define main method to control all new threads. Step7: Stop the program. PROGRAM: class NewThread implements Runnable { String name; Thread t; NewThread(String threadname) { name= threadname; t=new Thread(this,name); System.out.println("new thread "+t); t.start(); } public void run() { try { for(int i=5;i>0;i--) {

CS2312-OBJECT ORIENTED PROGRAMMING LAB

System.out.println(name+":"+i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println(name+" Interrupted"); } System.out.println(name+" exiting"); } } class multiplethread { public static void main(String ags[]) { new NewThread("one"); new NewThread("two"); new NewThread("three"); try { Thread.sleep(10000); } catch(InterruptedException e) { System.out.println("main thread interrupted"); } System.out.println("main thread exiting"); } }

CS2312-OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

SUSPENDING, RESUMING AND STOPPING THREADS AIM: To write a java program for suspend,resume and stopping threads. ALGORITHM: Step1: Create a class that implements Runnable interface to handle threads. Step2: Create two threads that shares the CPU. Step3: Using start() method start the thread execution which begins at the run method. Step4: Using suspend() and resume() methods defined by thread pause and restart the execution of thread. Step5: Using stop() method to stop the thread after finishing its execution. PROGRAM: class newth implements Runnable { String name; Thread t; newth(String threadname) { name=threadname; t=new Thread(this,name); System.out.println("New thread: "+t); t.start(); } public void run() { try { for(int i=15;i>0;i--) { System.out.println(name+":"+i); Thread.sleep(200);

CS2312-OBJECT ORIENTED PROGRAMMING LAB

} } catch(InterruptedException e) { System.out.println(name+" interrupted"); } System.out.println(name+" exiting"); } } class susres { public static void main(String args[]) { newth ob1=new newth("one"); newth ob2=new newth("two"); try { Thread.sleep(1000); ob1.t.suspend(); System.out.println("Suspending thread one"); Thread.sleep(1000); ob1.t.resume(); System.out.println("Resuming thread one"); ob2.t.suspend(); System.out.println("Suspending thread two"); Thread.sleep(1000); ob2.t.resume(); System.out.println("Resuming thread two"); } catch(InterruptedException e) { System.out.println("Main thread interrupted"); } try { System.out.println("waiting for threads to finish"); ob1.t.join(); ob2.t.join();

CS2312-OBJECT ORIENTED PROGRAMMING LAB

} catch(InterruptedException e) { System.out.println("Main thread interrupted"); } System.out.println("Main thread exiting"); } }

OUTPUT:

CS2312-OBJECT ORIENTED PROGRAMMING LAB

CS2312-OBJECT ORIENTED PROGRAMMING LAB

You might also like