Skip to main content

OBJECT-ORIENTED PROGRAMMING

 

What is OBJECT-ORIENTED PROGRAMMING?

Object-oriented programming is a programming paradigm built on the concept of objects.

In Other Words, it is an approach to problem-solving where all computations are carried out using objects.


  1. Program is divided into small parts called objects.
  2. Object-oriented programming follows a bottom-up approach.
  3. Have access specifiers like private, public, protected, etc.
  4. Adding new data and functions is easy.
  5. Provides data hiding so it is more secure than procedural programming.
  6. Overloading is possible in object-oriented programming.
  7. Data is more important than function.
  8. Provides the ability to simulate real-world
  9. Examples: C++, Java, Python, C#, JavaScript, Ruby, PHP, VB.NE

TERMINOLOGIES

  • Class - A class is a group of objects that share common properties and behavior.It is a blueprint or template from which objects are created.
  • Object- Object is any real-world entity that can
    have some characteristics or which can perform some tasks. It is also
    called the instance of a class

For example, we can consider a car as a class that has characteristics like steering wheels, seats, brakes, etc.


Class - color. Red - an object of color



  • Constructor - Constructors are special
    methods whose name is the same as the class name. The constructors serve
    the special purpose of initializing the objects.


  • Interface - Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract.


  • Default constructor - The default constructor is the constructor which doesn’t take any argument. It has no parameters.


  • Parameterized constructor - The constructors that take some arguments are known as parameterized constructors.


  • Copy constructor - A copy constructor is a member function that initializes an object using another object of the same class.


  • Friend Function - It is basically a function that is used to access all private and protected members of classes.


  • Member Function - It is basically a function
    that can be declared as members of a class. It is usually declared
    inside the class definition and works on data members of the same class.


  • Destructor - It frees up the resources and
    memory occupied by an object. Destructors are automatically called when
    an object is being destroyed.


  • Subclass - The subclass is a part of
    Inheritance. The subclass is an entity, which inherits from another
    class. It is also known as the child class.


  • Superclass - Superclass is also a part of
    Inheritance. The superclass is an entity, which allows subclasses or
    child classes to inherit from itself.


  • Abstract Class - An abstract class is a
    special class containing abstract methods. The significance of abstract
    class is that the abstract methods inside it are not implemented and
    only declared. So as a result, when a subclass inherits the abstract
    class and needs to use its abstract methods, they need to define and
    implement them.


  • Abstract Method - An abstract method is a method that doesn’t have anybody.


  • Methods - A method is a procedure or function in OOPs Concepts. It is a set of instructions that are associated with an object.


  • Static Method - A static method is a method
    that belongs to a class, but it does not belong to an instance of that
    class and this method can be called without the instance or object of
    that class. Non-static methods can access any static method and static
    variable, without creating an instance of the object.


  • Overloading - Overloading is a compile-time polymorphism feature in which an entity has multiple implementations with the same name.


  • Overriding - Whereas Overriding is a runtime
    polymorphism feature in which an entity has the same name, but its
    implementation changes during execution.


  • Exception - An exception can be considered as
    a special event, which is raised during the execution of a program at
    runtime, that brings the execution to a halt.


  • Exception handling - It is the mechanism for
    identifying the undesirable states that the program can reach and
    specifying the desirable outcomes of such states.

    Try-catch is the most common method used for handling exceptions in the program.


    Garbage Collection: It refers to the mechanism of handling the memory in
    the program. Through garbage collection, the unwanted memory is freed
    up by removing the objects that are no longer needed.


  • Interface v/s Abstract class difference -
    Interface and abstract classes both are special types of classes that
    contain only the method declaration and not their implementation. But
    the interface is entirely different from an abstract class. The main
    difference between the two is that, when an interface is implemented,
    the subclass must define all its methods and provide its implementation.
    Whereas when an abstract class is inherited, the subclass does not need
    to provide the definition of its abstract method, until and unless the
    subclass is using it.

    Also, an abstract class can contain abstract methods as well as non-abstract methods


  • Private - The access level of a private modifier is only within the class. It cannot be accessed from outside the class.


  • Default - The access level of a default
    modifier is only within the package. It cannot be accessed from outside
    the package. If you do not specify any access level, it will be the
    default.


  • Protected - The access level of a protected
    modifier is within the package and outside the package through child
    class. If you do not make the child class, it cannot be accessed from
    outside the package.


  • Public - The access level of a public
    modifier is everywhere. It can be accessed from within the class,
    outside the class, within the package and outside the package.

Why we use object-oriented programming?

Object-oriented programming is the programming paradigm that
is defined using objects. Objects can be considered as real-world
instances of entities like class, that have some characteristics and
behaviors.


  • OOPs helps users to understand the software easily, although they don’t know the actual implementation.
  • With OOPs, the readability, understandability, and maintainability of the code increases multifold.
  • Even very big software can be easily written and managed easily using OOPs.

What are the main features of OOPs?

Data Abstraction

  1. Data abstraction refers to providing only essential information
    about the data to the outside world, hiding the background details or
    implementation.
  2. Hiding the implementation and displaying only the functionality to the users.

Advantages

  1. It reduces the complexity of viewing things.
  2. Reduces the duplication of the code

Real Life Example

Consider a real-life example of a man driving a car. The man
only knows that pressing the accelerators will increase the speed of the
car or applying brakes will stop the car but he does not know about how
on pressing the accelerator the speed is actually increasing, he does
not know about the inner mechanism of the car or the implementation of
the accelerator, brakes, etc in the car.


Encapsulation

It describes the idea of bundling data and methods that work on that data within one unit.


Advantages

  1. Encapsulation protects an object from unwanted access by clients.
  2. Simplifies the maintenance of the application

Real Life Example

A Real-Life Example of Encapsulation is a School Bag.


Polymorphism

The word polymorphism means having many forms. It describes
the concept that different classes can be used with the same interface.

Polymorphism is the ability of any data to be processed in more than one form.


Polymorphism is divided into two types:


  • Compile Time Polymorphism - Compile time
    polymorphism, also known as Static Polymorphism, refers to the type of
    Polymorphism that happens at compile time. What it means is that the
    compiler decides what shape or value has to be taken by the entity in
    the picture.
  • Runtime Polymorphism - Runtime polymorphism, also
    known as Dynamic Polymorphism, refers to the type of Polymorphism that
    happens at the run time. What it means is it can't be decided by the
    compiler. Therefore what shape or value has to be taken depends upon the
    execution. Hence the name Runtime Polymorphism.

Advantages

  1. It helps the programmer to reuse the codes, i.e. classes once
    written, tested and implemented can be reused as required. Saves a lot
    of time.
  2. A single variable can be used to store multiple data types.

Real Life Example

Like a man at the same time is a father, a husband, an
employee. So the same person possesses different behavior in different
situations. This is called polymorphism.


Inheritance

Inheritance is a feature of OOPs which allows subclasses classes to inherit properties from the parent class.


Types of Inheritance



  • Single inheritance - When a class inherits from a single class, it is known as a single inheritance

  • Multiple inheritances - Multiple inheritances come into the picture when a class inherits from more than one base class.


    Parent 1 && Parent2 → child

  • Multilevel inheritance - When there is a chain of inheritance, it is known as multilevel inheritance.


    Example: Animal → Dog → Puppy

    Puppy Inherits from the Dog Class, Dog class inherits from the Class Animal.

  • Hierarchical inheritance - When two or more classes inherit a single class, it is known as hierarchical inheritance.


    Example: Animal → Dog = Cats

  • Hybrid inheritance - Hybrid inheritance is a combination of multiple and multi-level inheritances.

Advantages

The main advantages of inheritance are code reusability and
readability. When a child class inherits the properties and
functionality of the parent class, we need not to write the same code
again in the child class. This makes it easier to reuse the code, makes
us write less code and the code becomes much more readable.


Real Life Example

If there is a class such as ‘vehicle’, other classes like
‘car’, ‘bike’, etc can inherit common properties from the vehicle class.


What is Overloading and Overriding?

When two or more methods in the same class have the same name but different parameters, it's called Overloading.


When the method name and parameters are the same in the superclass and the child class, it's called Overriding.





SL
Overloading
Overriding




1
Method overloading is a compile-time polymorphism.
Method overriding is a run-time polymorphism.


2
It helps to increase the readability of the program.
It is used to grant the specific implementation of the method which is already provided by its parent class or superclass.


3
It occurs within the class.
It is performed in two classes with inheritance relationships.


4
Method overloading may or may not require inheritance.
Method overriding always needs inheritance.


5
In method overloading, methods must have the same name and different signatures.
In method overriding, methods must have the same name and same signature.


6
In method overloading, the return type can or can not be the same, but we just have to change the parameter.
In method overriding, the return type must be the same or co-variant.


Overloading and Overriding in JavaScript

JavaScript does not support function overloading natively. If
we will add functions with the same name and different arguments, it
considers the last defined function.


It is true that JavaScript supports overriding not overloading.
When you define multiple functions which has the same name, the last one
defined will override all the previously defined ones and every time
when you invoke a function, the last defined one will get executed.


Code Examples

Data Abstraction

JavaScript is a weakly typed language and does not have the
classical built-in support for abstraction like OOP languages. Instead,
JavaScript has the capability to support OOP, and thus can achieve OOP
functionalities, which is known as Object Oriented JavaScript (OOJS).
Data abstraction can be achieved by inheritance and composition.


In JavaScript, prototypes and closures can help us accomplish data abstraction.



function Employee(name, age, baseSalary) {
this.name = name;
this.age = age;
this.baseSalary = baseSalary

let monthlyBonus = 1000;

// This is not exposed to the user
let calculateMonthlyBonus = function () {
let finalSalary = baseSalary + monthlyBonus
console.log("Final Salary is : ", finalSalary)
}

this.getEmpDetails = function () {
console.log("Name: " + this.name,
"Age: " + this.age,
"baseSalary: " + this.baseSalary)
}
calculateMonthlyBonus()
}

let emp1 = new Employee("John", 30, 2000);
emp1.getEmpDetails()

OUTPUT : Final Salary is : 3000
Name: John Age: 30 baseSalary: 2000

Encapsulation

It describes the idea of bundling data and methods that work on that data within one unit.



class Employee {
setEmpDetails(name, id, phone) {
this.name = name;
this.id = id;
this.phone = phone;
}

getEmpName() {
console.log(this.name);
}
getEmpId() {
console.log(this.id);
}
getEmpPhoneNo() {
console.log(this.phone);
}
}

let emp1 = new Employee()
emp1.setEmpDetails("John", 319, 9788786086)
emp1.getEmpName();

OUTPUT : John

Polymerphism

It is the ability to create a variable , a function or an object that has more than one form.



class Animal{

constructor(name){
this.name = name;
}

eats(){
console.log(this.name, "eat food")
}
}


class Alligator extends Animal{

eats(){
console.log(this.name, "eat fishes")
}
}

let murphy = new Alligator("Murphy");
murphy.eats()

OUTPUT : Murphy eats fishes

Inheritance


class Car {
setName(name) {
this.name = name;
}

startEngine() {
console.log("Engine started For " + this.name);
}
stopEngine() {
console.log("Engine stopped For " + this.name);
}
}

class Toyota extends Car {

topSpeed(speed) {
console.log("Top Speed For " + this.name + " is " + speed);
}
}

let myCar = new Toyota();
myCar.setName("Camry");
myCar.startEngine()
myCar.stopEngine()
myCar.topSpeed(200)


OUTPUT :
Engine started For Camry
Engine stopped For Camry
Top Speed For Camry is 200




Comments

Popular posts from this blog

Create a socket for HTTP for web page upload and download

Create a socket for HTTP for web page upload and download. Aim: To write a java program for socket for HTTP for web page upload and download . Algorithm 1.Start the program. 2.Get the frame size from the user 3.To create the frame based on the user request. 4.To send frames to server from the client side. 5.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client. 6.Stop the program Program : Client import javax.swing.*; import java.net.*; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Client{ public static void main(String args[]) throws Exception{ Socket soc; BufferedImage img = null; soc=new Socket("localhost",4000); System.out.println("Client is running. ");  try { System.out.println("Reading image from disk. "); im...

Write an HTML program to design an entry form of student details and send it to store at database server like SQL, Oracle or MS Access

Write an HTML program to design an entry form of student details and send it to store at database server like SQL, Oracle or MS Access <!DOCTYPE html> <html> <head> <title>PHP insertion</title> <link href="css/insert.css" rel="stylesheet"> </head> <body> <div class="maindiv"> <!--HTML Form --> <div class="form_div"> <div class="title"> <h2>Insert Data In Database Using PHP.</h2> </div> <form action="insert.php" method="post"> <!-- Method can be set as POST for hiding values in URL--> <h2>Form</h2> <label>Name:</label> <input class="input" name="name" type="text" value=""> <label>Email:</label> <input class="input" name="email" type="text" value=""> <label>Contact:</label> <inp...

Write a code simulating PING and TRACEROUTE commands

  Write a code simulating PING command     Aim:   To Write the java program for simulating ping command   Algorithm Step 1: start the program. Step 2: Include necessary package in java. Step 3: To create a process object p to implement the ping command. Step 4: declare one BufferedReader stream class object. Step 5: Get thedetails of the server          5.1: length of the IP address.          5.2: time required to get the details.          5.3: send packets , receive packets and lost packets.          5.4: minimum ,maximum and average times. Step 6: print the results. Step 7:Stop the program.   Program:   import java.io.*; import java.net.*; class pingserver { public static void main(String args[]) { try { String str; System.out.print(" Enter...