What is OOPS?
Object Oriented Programming is a programming concept that works on the principle that objects are the most important part of your program. It allows users create the objects that they want and then create methods to handle those objects. Manipulating these objects to get results is the goal of Object Oriented Programming.
Core OOPS concepts are:
- Class
- Object
- Abstraction
- Encapsulation
- Polymorphism
- Inheritance
- Association
- Aggregation
- Composition
Let’s look into these object oriented programming concepts one by one. We will use java programming language for code examples, so that you know how to implement OOPS concepts in java.
ClassThe class is a group of similar entities. It is only an logical component and not the physical entity. For example, if you had a class called “Expensive Cars” it could have objects like Mercedes, BMW, Toyota, etc. Its properties(data) can be price or speed of these cars. While the methods may be performed with these cars are driving, reverse, braking etc.
public class Website { //fields (or instance variable) String webName; int webAge; // constructor Website(String name, int age){ this.webName = name; this.webAge = age; } public static void main(String args[]){ //Creating objects Website obj1 = new Website("beginnersbook", 5); Website obj2 = new Website("google", 18); //Accessing object data through reference System.out.println(obj1.webName+" "+obj1.webAge); System.out.println(obj2.webName+" "+obj2.webAge); } }
Output:
beginnersbook 5 google 18
Object
A single object by itself may not be very useful. An application contains many objects. One object interacts with another object by invoking methods on that object. It is also referred to as Method Invocation. See the diagram below.

Abstraction
Abstraction is the concept of hiding the internal details and describing things in simple terms. For example, a method that adds two integers. The method internal processing is hidden from outer world. There are many ways to achieve abstraction in object oriented programming, such as encapsulation and inheritance.
A java program is also a great example of abstraction. Here java takes care of converting simple statements to machine language and hides the inner implementation details from outer world.
Encapsulation
Encapsulation is the technique used to implement abstraction in object oriented programming. Encapsulation is used for access restriction to a class members and methods.
Encapsulation example in Java
How to
1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.
1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.
class EmployeeCount { private int numOfEmployees = 0; public void setNoOfEmployees (int count) { numOfEmployees = count; } public double getNoOfEmployees () { return numOfEmployees; } } public class EncapsulationExample { public static void main(String args[]) { EmployeeCount obj = new EmployeeCount (); obj.setNoOfEmployees(5613); System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees()); } }
Output:
No Of Employees: 5613
The class
So what is the benefit of encapsulation in java programming
Well, at some point of time, if you want to change the implementation details of the class EmployeeCount, you can freely do so without affecting the classes that are using it.
EncapsulationExample
that is using the Object of class EmployeeCount
will not able to get the NoOfEmployees directly. It has to use the setter and getter methods of the same class to set and get the value.So what is the benefit of encapsulation in java programming
Well, at some point of time, if you want to change the implementation details of the class EmployeeCount, you can freely do so without affecting the classes that are using it.
Polymorphism
Polymorphism is the concept where an object behaves differently in different situations. There are two types of polymorphism – compile time polymorphism and runtime polymorphism.
This is a perfect example of polymorphism (feature that allows us to perform a single action in different ways).
Static Polymorphism:
Polymorphism that is resolved during compiler time is known as static polymorphism. Method overloading can be considered as static polymorphism example.
Method Overloading: This allows us to have more than one methods with same name in a class that differs in signature.
Method Overloading: This allows us to have more than one methods with same name in a class that differs in signature.
class DisplayOverloading { public void disp(char c) { System.out.println(c); } public void disp(char c, int num) { System.out.println(c + " "+num); } } public class ExampleOverloading { public static void main(String args[]) { DisplayOverloading obj = new DisplayOverloading(); obj.disp('a'); obj.disp('a',10); } }
Output:
a a 10
When I say method signature I am not talking about return type of the method, for example if two methods have same name, same parameters and have different return type, then this is not a valid method overloading example. This will throw compilation error.
Dynamic Polymorphism
It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime rather, thats why it is called runtime polymorphism.
Example
class Animal{ public void animalSound(){ System.out.println("Default Sound"); } } public class Dog extends Animal{ public void animalSound(){ System.out.println("Woof"); } public static void main(String args[]){ Animal obj = new Dog(); obj.animalSound(); } }
Output:
Woof
Inheritance
Inheritance is the object oriented programming concept where an object is based on another object. Inheritance is the mechanism of code reuse. The object that is getting inherited is called superclass and the object that inherits the superclass is called subclass.
we have a parent class
Teacher
and a child class MathTeacher
. In the MathTeacher
class we need not to write the same code which is already present in the present class. Here we have college name, designation and does() method that is common for all the teachers, thus MathTeacher class does not need to write this code, the common data members and methods can inherited from the Teacher
class.class Teacher { String designation = "Teacher"; String college = "Beginnersbook"; void does(){ System.out.println("Teaching"); } } public class MathTeacher extends Teacher{ String mainSubject = "Maths"; public static void main(String args[]){ MathTeacher obj = new MathTeacher(); System.out.println(obj.college); System.out.println(obj.designation); System.out.println(obj.mainSubject); obj.does(); } }
Output:
Beginnersbook Teacher Maths Teaching
Note: Multi-level inheritance is allowed in Java but not multiple inheritance


Types of Inheritance:
Single Inheritance: refers to a child and parent class relationship where a class extends the another class.
Single Inheritance: refers to a child and parent class relationship where a class extends the another class.
Multilevel inheritance: refers to a child and parent class relationship where a class extends the child class. For example class A extends class B and class B extends class C.
Hierarchical inheritance: refers to a child and parent class relationship where more than one classes extends the same class. For example, class B extends class A and class C extends class A.
Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a child class has two parent classes. Java doesn’t support multiple inheritance, read more about it here.
Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++.
Association
Association is the OOPS concept to define the relationship between objects. Association defines the multiplicity between objects. For example Teacher and Student objects. There is one to many relationship between a teacher and students. Similarly a student can have one to many relationship with teacher objects. However both student and teacher objects are independent of each other.
Association Example
class CarClass{ String carName; int carId; CarClass(String name, int id) { this.carName = name; this.carId = id; } } class Driver extends CarClass{ String driverName; Driver(String name, String cname, int cid){ super(cname, cid); this.driverName=name; } } class TransportCompany{ public static void main(String args[]) { Driver obj = new Driver("Andy", "Ford", 9988); System.out.println(obj.driverName+" is a driver of car Id: "+obj.carId); } }
Output:
Andy is a driver of car Id: 9988
In the above example, there is a one to one relationship(Association) between two classes:
CarClass
and Driver
. Both the classes represent two separate entitiesAggregation
Aggregation is a special type of association. In aggregation, objects have their own life cycle but there is an ownership. Whenever we have “HAS-A” relationship between objects and ownership then it’s a case of aggregation.
Aggregation Example in Java
For example consider two classes
Student
class and Address
class. Every student has an address so the relationship between student and address is a Has-A relationship. But if you consider its vice versa then it would not make any sense as an Address
doesn’t need to have a Student
necessarily. Lets write this example in a java program.Student Has-A Address
class Address { int streetNum; String city; String state; String country; Address(int street, String c, String st, String coun) { this.streetNum=street; this.city =c; this.state = st; this.country = coun; } } class StudentClass { int rollNum; String studentName; //Creating HAS-A relationship with Address class Address studentAddr; StudentClass(int roll, String name, Address addr){ this.rollNum=roll; this.studentName=name; this.studentAddr = addr; } public static void main(String args[]){ Address ad = new Address(55, "Agra", "UP", "India"); StudentClass obj = new StudentClass(123, "Chaitanya", ad); System.out.println(obj.rollNum); System.out.println(obj.studentName); System.out.println(obj.studentAddr.streetNum); System.out.println(obj.studentAddr.city); System.out.println(obj.studentAddr.state); System.out.println(obj.studentAddr.country); } }
Output:
123 Chaitanya 55 Agra UP India
The above example shows the Aggregation between Student and Address classes. You can see that in Student class I have declared a property of type Address to obtain student address
Composition
Composition is a special case of aggregation. Composition is a more restrictive form of aggregation. When the contained object in “HAS-A” relationship can’t exist on it’s own, then it’s a case of composition. For example, House has-a Room. Here room can’t exist without house.
Advantages of OOPS:
Advantages of OOPS:
- OOP offers easy to understand and a clear modular structure for programs.
- Objects created for Object-Oriented Programs can be reused in other programs. Thus it saves significant development cost.
- Large programs are difficult to write, but if the development and designing team follow OOPS concept then they can better design with minimum flaws.
- It also enhances program modularity because every object exists independently.
read out the above concept it is a interesting...
ReplyDeleteFibonacci Series in Java without using recursion
ReplyDeleteclass FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}
Wrapper class in Java
ReplyDeleteWrapper class in java provides the mechanism to convert primitive into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing.
The eight classes of java.lang package are known as wrapper classes in java. The list of eight wrapper classes are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Instance Variable in Java
ReplyDeleteInstance variable in java is used by Objects to store their states. Variables which are defined without the STATIC keyword and are Outside any method declaration are Object specific and are known as instance variables.
Example of Instance Variable
class Page {
public String pageName;
// instance variable with public access
private int pageNumber;
// instance variable with private access
}