A beginner guide for OOPS Concept – Coder in Me

Misconception of OOPS Concept

As a programming student(Beginner) we are very much afraid of things like pointer, overloading , overriding, wrapper class, friend functions and the most famous Object Oriented Approach.Although we know the definition of Object and Class , and all oops concept but we are very confused in our practical implementation through our bookish language definition.We often think that data hiding and abstraction are same. or we say that polymorphism is driven from inheritance. So there are so much misconception because we have never used it in practical coding till now as a newbies.

To overcome all of these let’s start from the beginning.

First let’s clarify the very basic topic, CLASS & OBJECTS

What you see in this pictures.

OOPS Concept

There are different Vehicles, IT Companies and Cookies, these all are termed as CLASS. Any particular think from this class either of Vehicles or of IT Company or Cookies, say “SUV” or “Yahoo” or “Chocolate cookies” said to be an object; that means for similar things which have some common attributes or properties we have a Class for them. Thus, any one of them will be an object. If Coderinme is an IT company  then it have some or all properties of Above companies list, So coderinme is an object.

In our traditional approach what we did ?

We define six types of variables with different function name meanwhile some properties were same like every car or vehicle  have wheel, brake, light, accelearator, body etc.

But for SUV we will make a function and use it for maruti_suzuki also.To create a new function is not good practice. Duplicate data, dynamic changes errors are popular in traditional.

OOPS Concept

So we make a class in OOPS concept

Like

OOPS Concept

Now if we will create an object  like

Company c1;

c1 = new Company();

OR

Company c1=new Company();

to use all the functions or method (like start() ) and make use of all the variables itself by the Class.

Syntax in C++
Class Company{
public :
string name;
string reg_no;
int phone;
};

//main 
int main(){
Company c1;
Company c2;
c1.name="COderinme";
return 0;
}

Syntax in Java

class Company{  
 int id;//field or data member or instance variable  
 String name;
 
 
 
 public static void main(String args[]){  
  Company c1=new Student();//creating an object of Company
  System.out.println(c1.id);//accessing member through reference variable  

 }  
}
DAta Hiding

Suppose you have a fan and a switch. If you want to start the fan, you just need to switch-on the button and fan will automatically start. You don’t need to know how it will work. What is the function of switch or we can say about its internal working. You just know that it is the switch for fan.
Exactly the same thing we are doing in our Object Concept. If we want to add 3 numbers we will call add function. We don’t need to know how that function will work.

Example:
Consider you have a mobile phone, you just need to know what buttons are to be pressed to send a message or make a call, you don’t need to bother about its internal functioning. What happens when you press a button, how your messages are sent, how your calls are connected is all abstracted away from the user. That is the concept of Data hiding.

Coding Term

In general data hiding is a technique, where we restrict the user to see how much data user can see. Some data are important and we should show it to user. Some specific data should be hidden.

Data Hiding is used to hide decision design , code logic, basic decision used in proper function.

class new{
private: d=3;
public: 
	int add(int a, int b, int c){
		return a+b%c -d;
	}
};


void main(){
	new a;
	cout<<a.add(5,20,6);
	// output will be 4
	
}

Here user don’t know how add function work ? Because he  doesn’t need to know he just want to execute add function

Note: Data hiding is used to restrict user to handle data in that manner which a developer or coder want.

Abstraction

Have you heard about the word abstract. Yes Often we used this in our report , thesis and dissertation. Now you are confused how that abstract is same here. First of all I have an example for you

Suppose you want to go for a long drive with your friend. You have many convenience like your bike (Discover), you friend’s Apache, your car, Your uncle’s avenger etc..

You can choose any of these according to your requirement, and you will choose that specific bike or car which will be best suitable for you, this is known as abstraction.

Thus, In Coding Language showing of specific and important data from many options is abstraction. In the above example variable ‘d’ is hidden from user.

Note: It is used for achieving security, unauthorized access and to choose best as per your requirements.

Encapsulation

Word “Capsule” is very popular which means 2 different medicine is combined together in a cylindrical shape. Here, ENCAPSULATION means we combine similar data and method together.

For example, in a shop there are sections define. In food section you will never find clothes all food, snacks, and edible items are put in food section; Clothes section combine men’s and women’s wear etc.

Hence,

What is the use of it?

  1. We don’t need to search where food, pulse, sugar, cold drink, is or where are jeans and all. Categorization will help you to find and memorize the thing.

In Coding, we make class for similar methods like for peter or sam or sara we have human class, for CoderInMe, Google, Adobe  we use ‘company’ class and for hero passion or apache, SUV  so we will use vehicle class that will help us to memorize the function and attribute of a car will be in vehicle class

  1. Best Practice for security, we use private, public, or protected access specifier because we can give a hint that which data can be accessed by another class or method.
  2. Note:  Make class members private by default unless we really need to expose them. That’s a good encapsulation.
Class human{
	private:
	string name;
	int age;
	...
	...
	
	public:
	void sleep(string n){
	 cout<<n<<" is sleeping don't interrupt";
	}
	boolean smartness(string c, float h, boolean l){
	boolean s=false;
	 if(c=='Fair' || h>=6 && l==true)
	 	s=true;
	 return s;
	}
};



 main(){
human neha;

string c="Fair";
float h=5.4;
boolean l=true;
 if(neha.smartness(c,h,l)==true)
 	cout<<"Neha is smart";
 else cout<<"Neha is not smart";


}
Polymorphism

Poly means ‘many’, It means polymorphism is a definition for 1 thing in many form.

For example, an add function can add 2 integers, but it can be used to add 2 floats, or 3 integers, one integer and 2 floats etc.

In C, we can’t do it directly using the same add function.

For integer we will use,

int add1(int a, int b);

float  float add2(float a, float b , float c);

for n types we will need n method/functions. To overcome these problems oop concepts came with polymorphism concept.

Algorithm:

program

function Add(s, f : Integer) : Integer;
begin
    Add := s + f
end;

function Add(s, f : String) : String;
begin
    Add := Concat(s, f)
end;

begin
    cout<<(Add(21, 12));                   (* Prints 33            *)
    cout<<(Add('Coder in ', 'Me!'));    (* Prints "Coder in Me!" *)
end.

How to achieve polymorphism?

 Two Types:

Static Polymorphism: It is achieved through function overloading and operator overloading. It is always faster. It is also called as compile time polymorphism.

Example of static polymorphism is method overriding using final or private methods. At the compilation time for java user java knows which method is call by checking the arguments, so it is also known as early binding or static binding.

Types of static polymorphism :

    • Function Overloading: It is nothing but the ability of one function performs different tasks. These functions must differ by the data types. To call function the same function name is used for various instances.
    • int add(int x, int y)
      {
       cout << x+y;
      }
      
      int add(int x, int y, int z)
      {
       cout << x+y+z;
      }
      Here add() function is overloaded, to have 2 & 3 arguments. Which sum() function will be called, depends on the number of arguments.
      
      int main()
      {
      add(10,20);  // sum() with 2 parameter will be called
      
      add(10,20,30);  //sum() with 3 parameter will be called
      }

      Note :

      sum (int x,int y=0,int z);  // This is incorrect
      sum (int x,int y=10,int z=10);  // Correct
    • Operator overloading
Box3 = Box1 + Box2;

here box 1 box2 has length , height and breadth. we want to find 3rd box which is equal to box1+box2
 // Overload + operator to add two Box objects.
      Box operator+(const Box& b) {
         Box box;
         box.length = this->length + b.length;
         box.breadth = this->breadth + b.breadth;
         box.height = this->height + b.height;
         return box;
      }

Note: this thing can be used within one class.

But if we have 2 class with the same method name in different form , we use overriding.

In That case, compiler call that method in which class , object is defined.

Dynamic Polymorphism

It is also called as run-time polymorphism,  for this we use overridden method is invoking through the super class reference variable. Like Friend function.

It can be achieved by method overriding.

Method overriding  is to define a method with same name and  signature in the base/Parent class as well as in the derived/child  class.That means you define a method(Constructor) in the parent class. Then you redefine the same method in the child class also then we call that the method is overridden by the derived class.

class Child //parent class
{
	public void speak()//define method
	{
	System.out.println("Children speak  mother tounge.");				
	}
}
 
 
class Genius extends Child //extend parent class to override
{
	public void speak(){ //override method
		System.out.println("Students can speak in any language.");
	}
}
 
class Test
{
	public static void main(String[] args)//main method
	{	//create object of Children and Student class
		Child c = new Child();
		Genius  g = new Genius ();
		
		// call method
		c.speak();
		g.speak();
	}

}
  OOPS Concept

So that’s all for now we will briefly discuss each topic with example in next article , till then believe in coding and say I have a coder in me.

 for practice  click
  1. Object Based Question in C++
  2. Class and object
  3. object basic program

 

All rights reserved. Hence No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. Finally For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.