0% found this document useful (0 votes)
2 views

Object Orienteted ProgrammingI(26!03!25)

Object-Oriented Programming (OOP) utilizes objects to model real-world entities and aims to encapsulate data and functions, promoting easier software maintenance and adaptability. Key concepts of OOP include classes, objects, inheritance, encapsulation, and polymorphism, which enhance code reusability and structure. Java exemplifies OOP principles through its class and object constructs, allowing for efficient program design and implementation.

Uploaded by

sarithainti444
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Object Orienteted ProgrammingI(26!03!25)

Object-Oriented Programming (OOP) utilizes objects to model real-world entities and aims to encapsulate data and functions, promoting easier software maintenance and adaptability. Key concepts of OOP include classes, objects, inheritance, encapsulation, and polymorphism, which enhance code reusability and structure. Java exemplifies OOP principles through its class and object constructs, allowing for efficient program design and implementation.

Uploaded by

sarithainti444
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

NEED FOR OOP PARADIGM

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.

Procedural programming is about writing procedures or methods that perform operations on


the data, while object-oriented programming is about creating objects that contain both data
and methods.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute.


 OOP provides a clear structure for the programs.
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug.
 OOP makes it possible to create full reusable applications with less code and shorter
development time.

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 WORLD

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.

Agents and Communities


To solve my food delivery problem, I used a solution by finding an appropriate agent
(Zomato) and pass a message containing my request. It is the responsibility of the agent
(Zomato) to satisfy my request. Here, the agent uses some method to do this. I do not need to
know the method that the agent has used to solve my request. This is usually hidden from me.
So, in object-oriented programming, problem-solving is the solution to our problem which
requires the help of many individuals in the community. We may describe agents and
communities as follows.
An object-oriented program is structured as a community of interacting agents, called
objects. Where each object provides a service (data and methods) that is used by other
members of the community.
In our example, the online food delivery system is a community in which the agents are
zomato and set of hotels. Each hotel provides a variety of services that can be used by other
members like zomato, myself, and my family in the community.

Messages and Methods


To solve my problem, I started with a request to the agent zomato, which led to still more
requestes among the members of the community until my request has done. Here, the
members of a community interact with one another by making requests until the problem has
satisfied.
In object-oriented programming, every action is initiated by passing a message to an
agent (object), which is responsible for the action. The receiver is the object to whom
the message was sent. In response to the message, the receiver performs some method to
carry out the request. Every message may include any additional information as
arguments.
In our example, I send a request to zomato with a message that contains food items, the
quantity of food, and the hotel details. The receiver uses a method to food get delivered to my
home.

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 and Instances


In object-oriented programming, all objects are instances of a class. The method invoked by
an object in response to a message is decided by the class. All the objects of a class use the
same method in response to a similar message.
In our example, the zomato a class and all the hotels are sub-classes of it. For every request
(message), the class creates an instance of it and uses a suitable method to solve the problem.

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.

Principles(or) Concepts of Object Oriented Programming


The major Concepts of Object Oriented Programming are:
1. Class
2. Object
3. Abstraction
4. Encapsulation
5. Data Hiding
6. Inheritance
7. Reusability
8. Polymorphism
9. Virtual Functions
10. Message passing

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.

e.g.: employee e1, e2;


In the above example employee is the class name and e1 and e2 are objects of that class.

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.

There are two types of abstraction


i) Procedural Abstraction
ii) Data Abstraction

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.

e.g: structure, class.


Encapsulation: Encapsulation is the process of combining data members and member functions into a
single unit as a class in order to hide the internal operations of the class and to support abstraction.

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.

 Identity - It is the name given to the class.


 State - Represents data values that are associated with an object.
 Behavior - Represents actions can be performed by an object.

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.

 A class is declared by use of the class keyword.


 A class is an entity that determines how an object will behave and what the object will
contain.
 A class is a blueprint from which individual objects are created. It represents the set of
properties or methods that are common to all objects of one type.

 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

<ClassName> <objectName> = new <ClassName>( );

↓_ The objectName must begin with an alphabet, and a Lower-case letter is preferred.
_↓ The objectName must follow all naming rules.

Object And Class Example: Main Within the Class

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

1. //Java Program to illustrate how to define a class and fields


2. //Defining a Student class.
3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
14. }
15. }

Output:

0
null

Object and Class Example: main outside the class

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

1. //Java Program to demonstrate having the main method in


2. //another class
3. //Creating Student class.
4. class Student{
5. int id;
6. String name;
7. }
8. //Creating another class TestStudent1 which contains the main method
9. class TestStudent1{
10. public static void main(String args[]){
11. Student s1=new Student();
12. System.out.println(s1.id);
13. System.out.println(s1.name);
14. }
15. }

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.

What are Constructors in Java?


In Java, Constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling the constructor, memory for the object is
allocated in the memory. It is a special type of method that is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
Note: It is not necessary to write a constructor for a class. It is because the java compiler
creates a default constructor (constructor with no arguments) if your class doesn’t have
any.

How Java Constructors are Different From Java Methods?


 Constructors must have the same name as the class within which it is defined it
is not necessary for the method in Java.
 Constructors do not return any type while method(s) have the return type
or void if does not return any value.
 Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.

Need of Constructors in Java


Think of a Box. If we talk about a box class then it will have some class variables (say
length, breadth, and height). But when it comes to creating its object(i.e Box will now exist
in the computer’s memory), then can a box be there with no value defined for its
dimensions? The answer is No.
So constructors are used to assign values to the class variables at the time of object
creation, either explicitly done by the programmer or by Java itself (default constructor).

When Constructor is called?


Each time an object is created using a new() keyword, at least one constructor (it could be
the default constructor) is invoked to assign initial values to the data members of the same
class. Rules for writing constructors are as follows:
 The constructor(s) of a class must have the same name as the class name in
which it resides.
 A constructor in Java can not be abstract, final, static, or Synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state.
Like methods, a constructor also contains a collection of statements(i.e. instructions) that
are executed at the time of Object creation.

There are two rules defined for the constructor.


1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Constructors in Java


Now is the correct time to discuss the types of the constructor, so primarily there are three
types of constructors in Java are mentioned below:
 Default Constructor
 Parameterized Constructor
 Copy Constructor

1. Default Constructor in Java


A constructor that has no parameters is known as default the constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the compiler does
not create a default constructor. The default constructor changed into the parameterized
constructor. But Parameterized constructor can’t change the default constructor.

// Java Program to demonstrate Default Constructor

// Driver class
class ABC {

// Default Constructor
ABC()
{
System.out.println("Default constructor");
}
// Driver function
public static void main(String[] args)
{
ABC obj = new ABC();
}
}

Output: Default constructor

2. Parameterized Constructor in Java


A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with our own values, then use a parameterized constructor.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
1. //Java Program to demonstrate the use of the parameterized constructor.
2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12. public static void main(String args[]){
13. //creating objects and passing values
14. Student4 s1 = new Student4(111,"Karan");
15. Student4 s2 = new Student4(222,"Aryan");
16. //calling method to display the values of object
17. s1.display();
18. s2.display();
19. }
20. }
Output:
111 Karan
222 Aryan

CONSTRUCTOR OVERLOADING IN JAVA

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.

Example of Constructor Overloading


1. //Java program to overload constructors
2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }

Output:
111 Karan 0
222 Aryan 25

DIFFERENCE BETWEEN CONSTRUCTOR AND METHOD IN JAVA

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

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 constructor is invoked implicitly. The method is invoked explicitly.

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.

JAVA COPY CONSTRUCTOR

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.

Use of Copy Constructor

We can use the copy constructor if we want to:

o Create a copy of an object that has multiple fields.


o Generate a deep copy of the heavy objects.
o Avoid the use of the Object.clone() method.
Advantages of Copy Constructor
o If a field declared as final, the copy constructor can change it.
o There is no need for typecasting.
o Its use is easier if an object has several fields.
o Addition of field to the class is easy because of it. We need to change only in the copy
constructor.

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.

There are five types of inheritances, and they are as follows.

 Simple Inheritance (or) Single Inheritance


 Multiple Inheritance
 Multi-Level Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

The following picture illustrates how various inheritances are implemented.

The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.

CREATING CHILD CLASS IN JAVA


In java, we use the keyword extends to create a child class. The following syntax used to
create a child class in java.
Syntax

class <ChildClassName> extends <ParentClassName>{


...
//Implementation of child class
...
}

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

Multilevel Inheritance Example

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...

Hierarchical Inheritance Example

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.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a method which


is already provided by its superclass.
o Method overriding is used for runtime polymorphism.

Rules for Java 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.

You might also like