object oriented programming tutorial

Object oriented Programming

Object oriented programming form the basics of all the programming that we do on major programming languages- C++, Java, Php, Python etc.

In this article we will cover all the major element of object oriented programming languages

Topics to be covered in this Object Oriented Programming article

  • Class
  • Object
  • Inheritance
  • Encapsulation
  • Abstraction
  • Polymorphism
  • Association, Composition and Aggregation

What is Class?

Let’s start with a question on “How can we define a car”?

Object Oriented Programming

Source: Pixabay

You will most probably say that it is an vehicle which helps us in moving from one place to another. This specific car is white, sporty, 2 seater Toyota Supra priced at approx. 50k dollars.

What information did you get from this

  • It’s a car
  • White color (Color)
  • Sport car (Type)
  • 2 seater (Seating capacity)
  • Toyota brand (Brand)
  • Supra model (Variant)
  • Cost 50k dollars (Price)

Now if we are into car showroom, we can make a table of each attributes (color, type, seating capacity, brand, model, price).

Now, our car showroom manager of agency (ABC) want to become hi-tech and store data of his all cars in some database through which he can access later through websites (like Autotrader, carsdirect etc) and let prospective buyers know about all the car.

In programming term, we have created a “Class” of cars. In this class, we have defined attributes like color, types, price, brand, model etc).

Now, think of examples where you can create class of mobile phone, ice cream, city etc.

Cars moves from one place to another with some speed (depending upon its horsepower, another variable). These set of actions which a class do/involved are called function.

Definition: Class is a blueprint or a set of instruction to build a specific type of object.

class <class_name>{

field;

method;

}

For our example of cars, we can define

Object oriented programming class

Key elements of Class

  • Class name: Should begin with initial letter (capitalized)
  • Modifiers: Class can be public or can have default access
  • Superclass: Class can be derived class from another base class. Class can extends its parent class.
  • Interface: Class can implement one or more interfaces.
  • Body: The class body surrounded by braces, { }.
  • Constructors: These are used for initializing new objects
  • Fields: These are variables that provides the state of the class and its objects
  • Methods: These are used to implement the behavior of the class and its objects.

What is object?

Let’s now think of scenario where all cars data is online, and customer visit website to browse list of the cars.

When he click to Toyota Supra, he will see details of Toyota Supra like color, price, brand, model, type etc

When he clicks to Honda Civic, he will see details of Honda Civic.

Now what is happening here is that each time customer click to any car model, a new type of car information is coming from class Car.

This means that every time a customer click, he is initiating a new class instance called object. This object will populate the webpage with list of attribute against the car selected.

Object Oriented Programming concepts

Source: Wikimedia

Definition: An object is a self-contained component which consists of methods and properties to generate the replica of the class.

Syntax

Cars toyotaSupra = new Cars();

Cars hondaCity = new Cars();

What is the Difference between Object & Class?

A class is a blueprint or prototype that defines the variables and the methods (functions) common to all objects of a certain kind.

An object is a specimen of a class. Software objects are often used to model real-world objects you find in everyday life. Each object contains list of variables and methods with respect to asked data.

Features of class in object oriented programming

  • Single Responsibility Principle (SRP) – Every class or module in a program should have responsibility for just a single piece of that program’s functionality.
  • Open Closed Responsibility (OCP) – Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”; that is, such an entity can allow its behavior to be extended without modifying its source code.
  • Liskov Substitution Responsibility (LSR) – Objects of a superclass shall be replaceable with objects of its subclasses without breaking the application. This requires the objects of your subclasses to behave in the same way as the objects of your superclass.
  • Dependency Inversion Principle (DIP) – High level modules should not depend on low level modules; both should depend on abstractions. Abstractions should not depend on details. Details should depend upon abstractions.
  • Interface Segregation Principle (ISP) – Clients should not be forced to implement interfaces they don’t use. Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one sub-module

Key features of Object

  • State: This is represented by attributes. Reflects properties of an object.
  • Behavior: This is represented by method. Reflects response of an object with other objects
  • Identity: Provides unique name to an object and enable one object to interact with other objects.

There are five different ways to create an object

  1. New operator
  2. newInstance() method
  3. newInstance() method of constructor
  4. clone() method
  5. Serialization and Deserialization

What is abstraction in OOP?

We all loved pizza, some of us like thin crust, some like extra cheese and some like pineapples toppings (yes these people exists).

OOP concepts

Now, think of this: Last time you visited a restaurant with your friends, and ordered a pizza of your choice, did you thought of what is happening in the oven, whether temperature is all right there. Or you just had casual chat with friends. It must be second option.

Pizza is an example of abstraction. You just need to place an order (call method to makePizza() with inputs regarding crust-type, toppings, cheese etc).

Class restaurant = new Restaurant();

restaurant.makePizza(crust-type,toppings, cheese);

In OOPs concept, this process is called abstraction which hides all the internal implementation details. You don’t need to understand how this method is implemented and which kinds of actions it has to perform to create the expected result. You just need to know which methods of the object are available to call and which input parameters are needed to trigger a specific operation.

Abstraction main goal is to handle complexity by hiding unnecessary details from the user. That enables the user to implement more complex logic on top of the provided abstraction without understanding or even thinking about all the hidden complexity.

What is inheritance?

Check this image first.

oop programming

Now answer this.

Q: What is relation between Car and Truck?

A: They both are vehicle. They will have things like tyres, engine, seat, etc. Altough shape, size will be different.

Q: What is relation between Electric car and Petrol Car?

A: They both are cars. They both will have  cars, engine, etc. Fuel type will be different.

Q: What is relation between Truck and Petrol Car?

A: They both are vehicles.

What are we seeing here.

We are seeing how we can derive Truck or Car from Vehicle Class. There will be certain parameters and functions that will be same and some will be unique to child.

Here we can take Vehicle as parent and Truck and Car as Child.

This mechanism is called Inheritance where you can to derive a class from another class for a hierarchy of classes that share a set of attributes and methods.

oop java tutorial

Base class is our original class just like Vehicle.

We derived new classes Truck and Cars from Vehicle. Now Vehicle become parent class or superclass . And Truck become subclass or child class or derived class.

We use the keyword extends to identify the class that your subclass extends. If you don’t declare a superclass, your class implicitly extends the class Object. Object is the root of all inheritance hierarchies; it’s the only class in Java that doesn’t extend another class.

Class Truck extends Vehicle

Super keywords in inheritance

Super keyword is called when superclass and subclass have same variable or method.

For example:

  • variable
  • method()

Visibility of Inherited class

inheritance

What is encapsulation?

Let’s take our old example of Pizza.

Now Class Pizza is used to create new instance of Pizza each time. There is a variable cheese which set quantity of cheese to lowest.

Now, as a cheese loving person, you want to upgrade the cheese option, and make it cheese burst (triple the normal cheese). You passed your cheese option to highest.

oops concepts

Key concepts in Encapsulation

In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. This is called as data hiding.

This concept is also often used to hide the internal representation, or state, of an object from the outside. If you have an attribute that is not visible from the outside of an object, and bundle it with methods that provide read or write access to it, then you can hide specific information and control access to the internal state of the object. We uses getter and setter method for reading and changing state of the variable.

Encapsulation is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. It describes the idea of bundling data and methods that work on that data within one unit

Key features of encapsulation

  1. Declare the variables of a class as private.
  2. Provide public setter and getter methods to modify and view the variables values.

Access modifiers

Programming languages like Java supports four access modifiers that you can use to define the visibility of classes, methods, and attributes. Access modifiers specify a different level of accessibility, and you can only use one modifier per class, method or attribute. You should always use the most restrictive modifier that still allows you to implement your business logic.

4 types of access modifiers

  • private
  • no modifier
  • protected
  • public

encapsulation

What is polymorphism

Consider these statements:

  • All cows are animals
  • All tigers are animals
  • All animals are not cows
  • No cows are tigers

First 2 statements suggest that there are 2 types of classes (Cow and Tiger) which are derived from similar base class (Animal). They share properties similar to animal (variable and methods) For example- Both of them eat.

But all animals are not cows. And neither are none cows are tigers. This mean each of animal types have some functions which are unique to themselves, inspite of that function is present in base class (Animal).

For example- Tiger eat so do Cow (same method)

But Tiger eat meat whereas Cow eat grass (method changed to specific animal)

This is called Polymorphism which allows objects of different classes (inherited from common base class) to provide more general actions defined for the base class. Each class will perform its class-specific operation when instructed to operate a specific method or return a value of its class member.

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any object that can pass more than one IS-A test is considered to be polymorphic.

Note: all objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

How is inheritance different from polymorphism

Just like inheritance, in polymorphism, one class inherits another class. In addition to inheritance, subclass can define specific features that are different from its ancestor.

Inheritance not only adds all public and protected methods of the superclass to your subclass, but it also allows you to replace their implementation.

Properties of reference variable in polymorphism

A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.

Reference variable should not be declared final

A reference variable can refer to any object of its declared type or any subtype of its declared type.

A reference variable can be declared as a class or interface type.

Example

Public interface Vegetarian{}

Public class Animal {}

Public class Cow extends Animal implements Vegetarian{}

Now, the Cow class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −

  • A Cow IS-A Animal
  • A Cow IS-A Vegetarian
  • A Cow IS-A Cow
  • A Cow IS-A Object

When we apply the reference variable facts to a Cow object reference, the following declarations are legal −

Example

Cow c = new Cow();

Animal a = c;

Vegetarian v = c;

Object o = c;

All the reference variables d, a, v, o refer to the same Cow object in the heap.

polymorphism

Methods Overloading in Object Oriented Programming

The method overloading feature is a technique to create two or more methods of the same name in a class having different signatures.

Method 1: public void bakePizza(crust type, cheese, toppings)

Method 2: public int bakePizza (pizzatype)

Both of these methods have same name, but their behaviors like input parameter and return type are different.

Method Overriding in Object Oriented Programming

A derived class method can be changed or overridden using the keyword override and that must be virtual or abstract in the base class. Doing this, we will have new implementation for the base class method having same name and signature.

See: Cow and Tiger example in polymorphism.

See also: Virtual method below

Method Hiding

Method hiding is nothing but invoking the hidden base class method when the base class variable reference is pointing to the derived class object.
This can be done by the new keyword in the derived class method implementation, in other words the derived class has the same method with the same name and signature.

Virtual Methods in Object Oriented Programming

Consider this:

All animals move and eat.

Let’s define our class Animal as:

oops virtual method

Now we create 2 animals- Wolf and Fish. Do you think that both will use same methods – Eat and Move.

No, each of these classes – Wolf and Fish, will create its own version of methods (eat and move) so to define with respect to that animal

virtual method polymorphism

What is virtual method?

These are method that can be re-defined in child classes.  These have implementation in both base and derived class. It is used when a method’s basic functionality is the same but sometimes more functionality is needed in the derived class. (Like fish swim and wolf run)

Virtual method is created in the base class using the virtual keyword and that method is overriden in the derived class using the override keyword. (Note that base class need to be overridden in derived class).

Note that it is an optional for the derived class to override the virtual method in a base class. But, base class need to specifically mention virtual keyword so that its method can be overridden.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

Virtual Method properties

  1. By default, methods are non-virtual. We can’t override a non-virtual method.
  2. We can’t use the virtual modifier with the static, abstract, private or override modifiers.

More Object Oriented Programming concepts

oop programming concepts

Association

Association refers to the relationship between multiple objects. It refers to how objects are related to each other and how they are using each other’s functionality. Composition and aggregation are two types of association.

Composition

The composition is the strong type of association. An association is said to composition if an Object owns another object and another object cannot exist without the owner object. Consider the case of Human having a heart. Here Human object contains the heart and heart cannot exist without Human.

Example of Composition

object oriented programming

oop aggregation

Aggregation

Aggregation is a weak association. An association is said to be aggregation if both Objects can exist independently. For example, a Restaurant object and a Pizza object. A restaurant contains multiple variants of pizzas but a pizza can exist without a restaurant.

Example of Aggregation

oops concepts

End note:

In this article, we have covered Object Oriented Programming (OOP) concepts in detail. If you have any doubt or confusion regarding object oriented programming, kindly write in comment box below or send us mail to info@xamnation.com

We are offering online learning courses for interview preparation and learning programming languages.

Check our key courses.

You can visit to Xamnation courses, and see the complete list yourself.

1 thought on “Object oriented Programming”

  1. Pingback: What is Linked List | Important interview questions - Xamnation

Leave a Comment

Your email address will not be published. Required fields are marked *