Object Orienteted ProgrammingI(26!03!25)
Object Orienteted ProgrammingI(26!03!25)
As the name suggests, Object-Oriented Programming or OOP refers to languages that use
objects in programming. They use objects as a primary source to implement what is to
happen in the code. Objects are seen by the viewer or user, performing tasks assigned by
you. Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism etc. in programming. The main aim of OOP is to bind together the
data and the functions that operate on them so that no other part of the code can access this
data except that function.
Object-oriented programming paradigm methods enable us to create a set of objects that work
together to produce software that is better understandable and models their problem domains
than those produced using traditional techniques. The software produced using an object-
oriented programming paradigm is easier to adapt to the changing requirements, easier to
maintain, create modules of functionality, promote greater design, be more robust, and
perform desired work efficiently.
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code.
You should extract out the codes that are common for the application and place them at a
single place and reuse them instead of repeating it.
Although, Java has become a popular programming language for developing the web-
application, android apps, IoT applications, etc. Still, C has not lost its popularity because it is
used to develop firmware, operating system, and other system utilities.
A way of viewing the world is an idea to illustrate the object-oriented programming concept
with an example of a real-world situation.
Let us consider a situation: I am at my office and I wish to get food to my family members
who are at my home from a hotel. Because of the distance from my office to home, there is
no possibility of getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delivery community), tell them
the variety and quantity of food and the hotel name from which I wish to deliver the food to
my family members. Look at the following image.
Responsibilities
In object-oriented programming, behaviors of an object described in terms of responsibilities.
In our example, my request for action indicates only the desired outcome (food delivered to
my family). The agent (zomato) free to use any technique that solves my problem. By
discussing a problem in terms of responsibilities increases the level of abstraction. This
enables more independence between the objects in solving complex problems.
Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes
(objects) of a community. This graphical representation shows classes listed in a hierarchical
tree-like structure. In this more abstract class listed near the top of the tree, and more specific
classes in the middle of the tree, and the individuals listed near the bottom.
In object-oriented programming, classes can be organized into a hierarchical
inheritance structure. A child class inherits properties from the parent class that higher
in the tree.
Method Binding, Overriding, and Exception
In the class hierarchy, both parent and child classes may have the same method which
implemented individually. Here, the implementation of the parent is overridden by the
child. Or a class may provide multiple definitions to a single method to work with
different arguments (overloading).
The search for the method to invoke in response to a request (message) begins with the
class of this receiver. If no suitable method is found, the search is performed in the parent
class of it. The search continues up the parent class chain until either a suitable method is
found or the parent class chain is exhausted. If a suitable method is found, the method is
executed. Otherwise, an error message is issued.
Class: Class is an abstract data type (user defined data type) that contains member variables and
member functions that operate on data. It starts with the keyword class. A class denotes a group of
similar objects.
e.g.: class employee
{
int empno;
char name[25],desg[25]; float sal;
public:
void getdata (); void putdata ();
};
Object: An object is an instance of a class. It is a variable that represents data as well as functions
required for operating on the data. They interact with private data and functions through public
functions.
Abstraction: Abstraction refers to the process of concentrating on the most essential features and
ignoring the details.
Abstraction is hiding the internal details and showing only essential functionality. In the
abstraction concept, we do not show the actual implementation to the end user, instead
we provide only essential things. For example, if we want to drive a car, we do not need
to know about the internal functionality like how wheel system works? how brake system
works? how music system works? Etc.
Procedural Abstraction: Procedural abstraction refers to the process of using user-defined functions
or library functions to perform a certain task, without knowing the inner details. The function should
be treated as a black box. The details of the body of the function are hidden from the user.
Data Abstraction: Data Abstraction refers to the process of formation of user defined data type from
different predefined data types.
Data Hiding: All the data in a class can be restricted from using it by giving some access levels
(visibility modes). The three access levels are private, public, protected.
Private data and functions are available to the public functions only. They cannot be accessed by the other
part of the program. This process of hiding private data and functions from the other part of the program
is called as data hiding.
Inheritance: Inheritance is the process of acquiring (getting) the properties of some other class. The class
whose properties are being inherited is called as base class and the class which is getting the properties is
called as derived class.
Base Class
Derived Class
Reusability: Using the already existing code is called as reusability. This is mostly used in inheritance.
The already existing code is inherited to the new class. It saves a lot of time and effort. It also reduces the
size of the program.
Polymorphism: Polymorphism means the ability to take many forms. Polymorphism allows to take
different implementations for same name.
Poly many
morphism forms
Polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviours. The java uses method
overloading and method overriding to implement polymorphism.
There are two types of polymorphism, Compile time polymorphism and run time polymorphism.
In Compile time polymorphism binding is done at compile time and in runtime polymorphism binding is
done at runtime.
e.g.: Function overloading, operator overloading.
e.g: Method overriding
Function Overloading: Function overloading is a part of polymorphism. Same function name having different
implementations with different number and type of arguments.
Operator Overloading: Operator overloading is a part of polymorphism. Same operator can have different
implementations with different data types.
Virtual Functions: Virtual functions are special type of functions which are defined in the base class and are
redefined in the derived class. When virtual function is called with a base pointer and derived object then the
derived class function will be called. A function can be defined as virtual by placing the keyword virtual for the
member function.
Message Passing: An object-oriented program contains a set of objects that communicate with one another. The
process of object oriented programming contains the basic steps:
1. Creating classes
2. Creating objects
3. Communication among objects
This communication is done with the help of functions (i.e., passing objects to functions).
CONCEPTS OF CLASSES
Java is an object-oriented programming language, so everything in java program must be
based on the object concept. In a java programming language, the class concept defines the
skeleton of an object.
The java class is a template of an object. The class defines the blueprint of an object. Every
class in java forms a new data type. Once a class got created, we can generate as many
objects as we want. Every class defines the properties and behaviors of an object. All the
objects of a class have the same properties and behaviors that were defined in the class.
Every class of java programming language has the following characteristics.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as
variables and behaviors as methods. Following is the syntax of class in the java.
Syntax
class <ClassName>{
data members declaration;
methods defination;
}
↓_ The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
↓_ The ClassName must follow all naming rules.
The data, or variables, defined within a class are called instance variables.
The code is contained within methods.
The methods and variables defined within a class are called members of the class.
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is
said to be instantiated. All the objects that are created using a single class have the same
properties and methods. But the value of properties is different for every object. Following is
the syntax of class in the java.
Syntax
↓_ The objectName must begin with an alphabet, and a Lower-case letter is preferred.
_↓ The objectName must follow all naming rules.
In this example, we have created a Student class which has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's
value.
Here, we are creating a main() method inside the class.
File: Student.java
Output:
0
null
In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main() method
in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.
File: TestStudent1.java
Output:
0
null
CONSTRUCTORS IN JAVA
Java constructors or constructors in Java is a terminology used to construct something in
our programs. A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used to set initial
values for object attributes.
// Driver class
class ABC {
// Default Constructor
ABC()
{
System.out.println("Default constructor");
}
// Driver function
public static void main(String[] args)
{
ABC obj = new ABC();
}
}
In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the list
and their types.
Now the most important topic that comes into play is the strong incorporation of OOPS
with constructors known as constructor overloading. Just like methods, we can overload
constructors for creating objects in different ways. The compiler differentiates constructors
on the basis of the number of parameters, types of parameters, and order of the parameters.
Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class name. The method name may or may not
be same as the class name.
In Java, a copy constructor is a special type of constructor that creates an object using another
object of the same Java class. It returns a duplicate copy of an existing object of the class.
We can assign a value to the final field but the same cannot be done while using the clone()
method. It is used if we want to create a deep copy of an existing object. It is easier to
implement in comparison to the clone() method.
In this example, we are going to copy the values of one object into another using Java
constructor.
1. //Java program to initialize the values from one object to another object.
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. }
Output:
111 Karan
111 Karan
Copy Constructor Vs clone() Method
Both the copy constructor and the clone() method are used to create a copy of an existing
object of the class. But the use of copy constructor is easier and better in comparison to the
clone() method because of the reasons given below:
o If we are using the clone() method it is necessary to import the Cloneable The
method may throw the exception CloneNotSupportException. So, handling the
exception in a program is a complex task. While in copy constructor there are no such
complexities.
o We cannot assign a value if the fields are final. While in the copy constructor we can
assign values to the final fields.
o The object returned by the clone() method must be typecast. While in copy
constructor there is no such requirement.
INHERITANCE CONCEPT
The inheritance is a very useful and powerful concept of object-oriented programming. In
java, using the inheritance concept, we can use the existing features of one class in another
class. The inheritance provides a great advantage called code re-usability. With the help of
code re-usability, the commonly used code in an application need not be written again and
again.
The inheritance can be defined as follows.
The inheritance is the process of acquiring the properties of one class to another class.
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.
The Parent class is the class which provides features to another class. The parent class is also
known as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also
known as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the parent
class never acquires the features from its child class.
The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.
Single Inheritance Example When a class inherits another class, it is known as a single
inheritance. In the example given below, Dog class inherits the Animal class, so there is the
single inheritance.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
Programmer salary is:40000.0
Bonus of programmer is:10000
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, C class inherits the B class which again inherits the A class, so
there is a multilevel inheritance.
class A{
void eat(){System.out.println("eating...");}
}
class B extends A{
void sleep(){System.out.println("sleeping...");}
}
class C extends B{
void enjoy(){System.out.println("enjoying...");}
}
class Test{
public static void main(String args[]){
C obj=new C();
obj.eat();
obj.sleep();
obj.enjoy();
}
}
Output:
eating...
sleeping...
enjoying...
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, B and C classes inherits the A class, so there is hierarchical
inheritance.
class A{
void eat(){System.out.println("eating...");}
}
class B extends A{
void sleep(){System.out.println("sleeping...");}
}
class C extends A{
void enjoy(){System.out.println("enjoying...");}
}
class Test{
public static void main(String args[]){
Cat c=new Cat();
c.enjoy();
c.eat();
//c.sleep();// Compile Time Error
}}
Output:
enjoying...
eating...
Method Overriding in Java
If the same method is defined in both the superclass and the subclass, then the method of the
subclass class overrides the method of the superclass. This is known as method overriding.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
1. The method must have the same name as in the parent class.
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
class A{
public void number() {
int a=10;
System.out.println("a="+a);
}
}
class B extends A {
@Override
public void number() {
int a=30;
System.out.println("a="+a);
}
}
class Main {
public static void main(String[] args) {
B s1 = new B();
s1.number();
}
}
Output: 30
The method overriding is the process of re-defining a method in a child class that
is already defined in the parent class. When both parent and child classes have
the same method, then that method is said to be the overriding method.
The method overriding enables the child class to change the implementation of
the method which acquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time.
The method binding which happens at run time is known as late binding. So, the
method overriding follows late binding.