Showing posts with label object oriented programming. Show all posts
Showing posts with label object oriented programming. Show all posts

Monday

operator overloading in c++ with example


Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type.



Almost any operator can be overloaded in C++. However there are few operator which can not be overloaded. Operator that are not overloaded are follows
  • scope operator - ::
  • sizeof
  • member selector - .
  • member pointer selector - *
  • ternary operator - ?:



Operator Overloading Example:
#include< iostream.h>
#include< conio.h>
class time
{
int h,m,s;
public:
 time()
 {
  h=0, m=0; s=0;
 }
 void getTime();
 void show()
 {
  cout<< h<< ":"<< m<< ":"<< s;
 }
time operator+(time);   //overloading '+' operator
};
time time::operator+(time t1) //operator function
{
time t;
int a,b;
a=s+t1.s;
t.s=a%60;
b=(a/60)+m+t1.m;
t.m=b%60;
t.h=(b/60)+h+t1.h;
t.h=t.h%12;
return t;
}
void time::getTime()
{
 cout<<"\n Enter the hour(0-11) ";
 cin>>h;
 cout<<"\n Enter the minute(0-59) ";
 cin>>m;
 cout<<"\n Enter the second(0-59) ";
 cin>>s;
}
void main()
{
clrscr();
time t1,t2,t3;
cout<<"\n Enter the first time ";
t1.getTime();
cout<<"\n Enter the second time ";
t2.getTime();
t3=t1+t2; //adding of two time object using '+' operator
cout<<"\n First time ";
t1.show();
cout<<"\n Second time ";
t2.show();
cout<<"\n Sum of times ";
t3.show();
getch();
}






Tuesday

Interface in Java and Object Oriented Programming

An interface s similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.
Java Interface also represents the IS-A relationship.It cannot be instantiated just like the abstract class. Since Java 8, we can have default and static methods in an interface. Since Java 9, we can have private methods in an interface.
read more......

Why use Java interface