Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

What Is Encapsulation: Different Types of Polymorphism

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

The word polymorphism is used in various contexts and describes situations in which something occurs in

several different forms. In computer science, it describes the concept that objects of different types can be
accessed through the same interface. Each type can provide its own, independent implementation of this
interface. It is one of the core concepts of object-oriented programming (OOP).

If you’re wondering if an object is polymorphic, you can perform a simple test. If the object successfully
passes multiple is-a or instanceof tests, it’s polymorphic. As I’ve described in my post about inheritance,
all Java classes extend the class Object. Due to this, all objects in Java are polymorphic because they pass
at least two instanceof checks.

Different types of polymorphism

Java supports 2 types of polymorphism:

 static or compile-time
 dynamic

: What is Encapsulation

Hiding internal state and requiring all interaction to be performed through an object's methods is known
as data encapsulation — a fundamental principle of object-oriented programming.

The main purpose or use of the encapsulation is to provide the security to the data of a class.

To make the data secure we need to use private access modifiers that will restrict the access to the data
outside the class. The access modifiers are used to define the access level or scope of the class members
like data members and functions.

The Object oriented programming provides the access modifiers like

 Private :-

The access scope of the private members are restricted to the class scope only, means private
members are not accessible or available from the another class.

 Default :-

It is not a keyword, if any access modifiers keyword is not defined then it will be considered as
default.

The access scope of the default members are restricted to the current or same package(folder).

The default members are not accessible or available from classes that are not present in the same
package.
 Protected :-

The access level or scope of the protected class members are restricted to within the current or
same package and from another package if and only if a class is inherited by the class from
another package.

 Public :-

The access modifier has widest scope mean the public class members can be accessed from any
class despite package of the classes and relationship.

Example: Here we are creating a data class.

class UserLogin
{
// private instance variables
private String username;
private String password;
public void setName(String name)
{
username = name;
}
public String getName()
{
return username;
}
public void setPassword(String pass)
{
password = pass;
}
public String getPassword()
{
return password;
}
}

Q3: What is Object as a Function Arguments


The objects of a class can be passed as arguments to member functions as well as nonmember functions
either by value or by reference. When an object is passed by value, a copy of the actual object is created
inside the function. This copy is destroyed when the function terminates. Moreover, any changes made to
the copy of the object inside the function are not reflected in the actual object. On the other hand, in pass
by reference, only a reference to that object (not the entire object) is passed to the function. Thus, the
changes made to the object within the function are also reflected in the actual object.

Example: A program to demonstrate passing objects by value to a member function of the same class
 
Q4: Define Inheritance and its types
However, inheritance may be implemented in different combinations in Object-Oriented Programming
languages as illustrated in figure and they include:

 Single Inheritance
 Multi Level Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
 Multipath inheritance
 Multiple Inheritance

Single Inheritance

When a Derived Class to inherit properties and behavior from a single Base Class , it is called as
single inheritance.

Multi Level Inheritance

A derived class is created from another derived class is called Multi Level Inheritance .

Hierarchical Inheritance

More than one derived classes are created from a single base class, is called Hierarchical Inheritance .

Any combination of above three inheritance (single, hierarchical and multi level) is called as hybrid
inheritance .

Multipath inheritance

Multiple inheritance is a method of inheritance in which one derived class can inherit properties of base
class in different paths.

Multiple inheritances allows programmers to create classes that combine aspects of multiple classes and
their corresponding hierarchies. In .Net Framework, the classes are only allowed to inherit from a single
parent class, which is called single inheritance

Q5: Define function overloading and Overriding ?


function overriding

Function overriding is a feature that allows us to have a same function that allows us to have a same
function in child class which is already present in the parent class. A child class inherits the data members
and member functions of parent class, but when you want to override a functionality in the child class
then you can use function overriding.

function overloading
Function overloading is a C++ programming feature that allows us to have more than one function having
same name but different parameter list. It means the data type and sequence of the parameters, for
example the parameters list of a function myfuncn (int a, float b) is (int, float).

Q6:What is constructor overloading?

Constructor overloading is a concept of having more than one constructor with different
parameters list, in such a way so that each constructor performs a different task. For e.g. Vector
class has 4 types of constructors.

Q:7 Define destructor ?


A destructor is a special member function of a class that is executed whenever an object of it's class goes
out of scope or whenever the delete expression is applied to a pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a
value nor can it take any parameters. Destructor can be very useful for releasing resources before coming
out of the program like closing files, releasing memories etc
Q8: Define Constructor and its types?

A class constructor is a special member function of a class that is executed whenever we create
new objects of that class.. A constructor will have exact same name as the class and it does not
have any return type at all, not even void. Constructors can be very useful for setting initial
values for certain member variables

Code sample

class Line {

  public:

    voidsetLength( doublelen );

    doublegetLength( void );

    Line();...

The various types of Constructor are as follows:


Default Constructor:  Default Constructor is also called as Empty Constructor which has no arguments and It  is
Automatically called when we creates the object of class  but Remember name of Constructor is same as name of
class and Constructor never declared with the help of Return Type. Means we cant Declare a Constructor with the
help of void Return Type. , if we never Pass or Declare any Arguments then this called as the Copy Constructors.
Parameterized Constructor: This is Another type  Constructor which has some Arguments and same name as class
name but it uses some Arguments So For this We have to create object of Class by passing some Arguments at the
time of creating object with the name of class. When we pass some Arguments to the Constructor then this will
automatically pass the Arguments to the Constructor and the values will retrieve by the Respective Data Members of
the Class.
Copy Constructor: This is also Another type of Constructor. In this Constructor we pass the object of class into the
Another Object of Same Class. As name Suggests you Copy, means Copy the values of one Object into the another
Object of Class .This is used for Copying the values of class object into an another object of class So we call them as
Copy Constructor and For Copying the values We have to pass the name of object whose values we wants to
Copying and When we are using or passing an Object to a Constructor then we must have to use the & Ampersand
or Address Operator.
Destructor: As we know that Constructor is that which is used for Assigning Some Values to data Members and
For Assigning Some Values this May also used Some Memory so that to free up the Memory which is Allocated by
Constructor, destructor is used which gets Automatically Called at the End of Program and we doesn’t have to
Explicitly Call a Destructor  and Destructor Cant be Parameterized or a Copy This can be only one Means Default
Destructor which Have no Arguments. For Declaring a Destructor we have to use ~tiled Symbol in front of
Destructor.

Q:9 Define Operator Overloading ?

Operator overloading means that the operation performed by the operator depends on the type of operands
provided to the operator. For example, (a) the bit left-shift operator << is overloaded to perform stream
insertion if the left operand is a ostream object such as cout; (b) the operator * could

means multiplication for two numbers of built-in types or indirection if it operates on an address. C++ lets
you extend operator overloading to user-defined types (classes).
Operator overloading is similar to function overloading, where you have many versions of the same
function differentiated by their parameter lists.

As an example, the C++ string class (in header <string>) overloads these operators to work


on string objects:
 String comparison (==, !=, >, <, >=, <=): For example, you can use str1 == str2 to compare the
contents of two string objects.
 Stream insertion and extraction (<<, >>): For example, you can use cout << str1 and cin >> str2 to
output/input string objects.
 Strings concatenation (+, +=): For example, str1 + str2 concatenates two string objects to produce a
new string object; str1 += str2 appends str2 into str1.
 Character indexing or subscripting []: For example, you can use str[n] to get the char at index n;
or str[n] = c to modify the char at index n. Take note that [] operator does not perform index-bound
check, i.e., you have to ensure that the index is within the bounds. To perform index-bound check,
you can use string's at() member function.
 Assignment (=): For example, str1 = str2 assigns str2 into str1.

1 /* Test overloaded operators in the C++ string class


2 (TestStringOverloadOperators.cpp) */
3 #include <iostream>
4 #include <iomanip>
5 #include <string> // needed to use the string class
6 using namespace std;
7
8 int main() {
9 string msg1("hello");
10 string msg2("HELLO");
11 string msg3("hello");
12
13 // Relational Operators (comparing the contents)
14 cout << boolalpha;
15 cout << (msg1 == msg2) << endl; // false
16 cout << (msg1 == msg3) << endl; // true
17 cout << (msg1 < msg2) << endl; // false (uppercases before lowercases)
18
19 // Assignment
20 string msg4 = msg1;
21
22 cout << msg4 << endl // Concatenation
23 cout << (msg1 + " " + msg2) << endl;
24 msg3 += msg2;
25 cout << msg3 << endl; //
26 cout << msg1[1] << endl; // 'e'
27 cout << msg1[99] << endl;
28
29
30
31
32

Q:10 What is Friend Class and friend function ?

IN C++ A friend class can access the private and protected members of the class in which it is declared as
a friend.

Another use of a friend class is for a part of a data structure, represented by a class, to provide access to
the main class representing that data structure

A friend function of a class is defined outside that class' scope but it has the right to access all private and
protected members of the class. Even though the prototypes for friend functions appear in the class
definition, friends are not member functions
Q:11 What is virtual function?

A virtual function is a member function that is declared within a base class and redefined by a derived
class. To create virtual function, precede the function’s declaration in the base class with the keyword
virtual. When a class containing virtual function is inherited, the derived class redefines the virtual
function to suit its own needs.

Q2: Define a base class shape with protected data members; width and height and setter
member functions for setting width and height, also define the derived class rectangle
publically inherited from class shape. Class rectangle should have a member function
getarea() which should compute and return area of a rectangle. Declare an object of
rectangle in main function and set its width and height then compute its area.

#include <iostream>

using namespace std;

class Shape {

public:

void setWidth(int w) {

width = w;

void setHeight(int h) {

height = h;

protected:

int width;
int height;

};

class Rectangle: public Shape {

public:

int getArea() {

return (width * height);

};

int main(void) {

Rectangle Rect;

Rect.setWidth(5);

Rect.setHeight(7);

cout << "Total area: " << Rect.getArea() << endl;

return 0;

Q3: (Modifying Question:2) Define another class named paint_cost with a member
function get_cost() which returns paint cost of the rectangle on the basis of its area; assume
cost=area*100. Inherit class rectangle from class shape and paint_cost.

#include <iostream>

using namespace std;

class Shape {
public:

void setWidth(int w) {

width = w;

void setHeight(int h) {

height = h;

protected:

int width;

int height;

};

class PaintCost {

public:

int getCost(int area) {

return area * 70;

};

class Rectangle: public Shape, public PaintCost {

public:

int getArea() {

return (width * height);

};
int main(void) {

Rectangle Rect;

int area;

Rect.setWidth(5);

Rect.setHeight(7);

area = Rect.getArea();

cout << "Total area: " << Rect.getArea() << endl;

cout << "Total paint cost: Rs." << Rect.getCost(area) << endl;

return 0;

Q4: Define a class display with three member functions named “print” first print function
should print an integer passed to it, the second function should print a floating passed to it
and third function should print a character array/string passed to it. Declare an object in
main function of the class you defined and test the functions you made.

#include <iostream>

using namespace std;

class printData {

public:

void print(int i) {

cout << "Printing int: " << i << endl;

void print(double f) {

cout << "Printing float: " << f << endl;


}

void print(char* c) {

cout << "Printing character: " << c << endl;

};

int main(void)

printData pd;

pd.print(5);

pd.print(50.26);

pd.print("Hello Superior");

return 0;

Q5: Define a class named; complex with two data members real and imaginary and
setter/getter member functions. Overload an addition “+” operator and multiplication “*”
operator for your class. Declare two objects in main function of the class you defined and
test the functions and operators you overloaded.
#include <iostream>

using namespace std;

class Complex {

public:

double getVolume(void) {

return length * breadth * height;

void setLength( double len ) {

length = len;

void setBreadth( double bre ) {

breadth = bre;

void setHeight( double hei ) {

height = hei;

Complex operator+(const Complex& b) {

Complex box;

box.length = this->length + b.length;

box.breadth = this->breadth + b.breadth;

box.height = this->height + b.height;

return box;

private:

double length;
double breadth;

double height;

};

int main() {

Complex Box1;

Complex Box2;

Complex Box3;

double volume = 0.0;

Box1.setLength(6.0);

Box1.setBreadth(7.0);

Box1.setHeight(5.0);

Box2.setLength(12.0);

Box2.setBreadth(13.0);

Box2.setHeight(10.0);

volume = Box1.getVolume();

cout << "Volume of Box1 : " << volume <<endl;

volume = Box2.getVolume();

cout << "Volume of Box2 : " << volume <<endl;

Box3 = Box1 + Box2;

volume = Box3.getVolume();

cout << "Volume of Box3 : " << volume <<endl;

return 0;

Q7: Create a class named 'Shape' with a function to print "This is a shape". Then create
two other classes named 'Rectangle' and 'Circle' inheriting the Shape class, both having a
function to print "This is rectangular shape" and "This is circular shape" respectively.
Then make pointer type object of shape class and apply polymorphism by using virtual
function.
#include<iostream>

using namespace std;

class Circle

protected:

float radius ;

public:

void Enter_r(void)

cout << "\n\t Enter the radius: "; cin >> radius ;

void Display_ca(void)

cout << "\t The area = " << (22/7 * radius*radius) ;

};

class Rectangle

protected:

float length, breadth ;

public:

void Enter_lb(void)

cout << "\t Enter the length & vreadth: ";

cin >> length >> breadth ;


}

void Display_ar(void)

cout << "\t The area = " << (length * breadth);

};

class Cylinder : public Circle, public Rectangle

public:

void volume_cy(void)

cout << "\t The volume of the cylinder is: "

<< (22/7* radius*radius*length) ;

};

int main()

{
Circle c ;

cout << "\n Getting the radius of the circle\n" ;

c.Enter_r( );

c.Display_ca( );

Rectangle r ;

cout << "\n\n Getting the length and breadth of the rectangle\n\n";

r.Enter_lb( );

r.Display_ar( );

Cylinder cy ;

cout << "\n\n Getting the height and radius of the cylinder\n";

cy.Enter_r( );

cy.Enter_lb( );

cy.volume_cy( );

return 0;

Q8: Create a class named 'A' with a function to print "A Class Function". Then create two
other classes named 'B' and 'C' inheriting the A class, both having a function to print "B
Class Function" and “C Class Function " respectively. Then make pointer type object of A
class and apply polymorphism by using virtual function.

# include <iostream>

using namespace std;

class A
{

public:

virtual void pp ()

cout<<" A Class Function :: "<<endl;

};

class B : public A

public:

void pp ()

cout<<"B Class Function :: "<<endl;

};

class C : public A

public:
void pp ()

cout<<"C Class Function :: "<<endl;

};

int main ()

A *p;

B a;

C b;

p=&a;

p-> pp();

p=&b;

p->pp();

You might also like