What is Object Oriented Programming for Beginners.
Object-Oriented Programming is a paradigm of programming, which states everything in an application is fundamentally an Object and its state at the given time. Object-Oriented Programming helps us avoid writing fragile, rigid, and non-reusable code. OOP has four fundamental notions that it strictly follows. They are Inheritance, Abstraction, Polymorphism, and Encapsulation. In the following section, we are going to look at each one of them in depth. but before that we need to understand what do we mean by object.
Objects and Classes
Objects are the basis of object-oriented programming because, in object-oriented programming, objects communicate with another Object to do any work. Some of the Real-world objects are Phone, Book, Television, Cat, etc. All object has a state in which they are currently in and related behavior according to those states. In OO as well the concept of object is similar. An object has several states and related behavior. Object store its states in fields or instance variable, and behavior is declared using methods or procedures.
Now then what is a class? Class is nothing but a blueprint on the basis of which these objects get created, JVM(Java Virtual Machine) or any other object-oriented compiler use these classes to create an object in memory. a class defines all the fields and methods that an object will be given at the time of its creation.
Forex. Dog object may have states such as runSpeed, height, color, etc. and behavior such as bark, fetchBall, etc. in this case bark behavior depends on the height of the dog. and fetchBall depends on running speed of a dog.
Inheritance
OO objects sometimes share similar properties with each other. PondBird and MountainBird classes defined in the below code pallet have a similar way of eating but they also have different methods that make them unique in themselves. inheritance is a way to decouple this common logic from objects and make it reusable so that code duplication can be avoided. please look at the following diagram to get a clear picture.
In the above diagram Bird class is a Base class of MountainBird and PondBird class, and these two classes are derived classes of Bird class. following is a sample code for the above example.
// Base or Parent Class
class Bird {
// All common things for Bird will go here.
public void eat() {
System.out.println("eat food");
}
}
// Derived or Child Classes
class PondBird extends Bird {
// All specific things to Pound Bird goes here.
public void swim() {
System.out.println("swims in pond");
}
}
class MountainBird extends Bird {
// All specific things to Mountain Bird goes here.
public void fly() {
System.out.println("fly in sky");
}
}
In above example PondBird and MountainBird both have inherited eat method from their base class and also have there own methods which is swim and fly respectively.
Polymorphism
Polymorphism is a biological principle which states that an organism or species can have multiple forms or stages. The same principle can be applied to OOP as well. The Subclasses of a class can define their unique traits and still share the same functionality as a parent class.
Now let us assume we have Aviary(a place where birds are kept). And we want to call a color method on all of those birds to see what color they are. We have lots of birds of different kinds, they all have different colors and all of them inherit from Bird class. To, do the above task, We can use runtime polymorphism or overriding. To store all different kinds of bird objects into a Bird Array, which is a parent class to all birds. At the run time, the color method will be called upon on those specific bird objects.
// Base or Parent Class
class Bird {
// All common things for Bird will go here.
public void eat() {
System.out.println("eat food");
}
public void color() {
System.out.println("yellow");
}
}
// Derived or Child Classes
class PondBird extends Bird {
// All specific things to Pound Bird goes here.
public void swim() {
System.out.println("swims in pond");
}
}
class MountainBird extends Bird {
// All specific things to Mountain Bird goes here.
public void fly() {
System.out.println("fly in sky");
}
@Override
public void color() {
System.out.println("Gray");
}
}/****************************************************************/class Main {
public static void main(String[] args) {
Bird bird1, bird2;
bird1 = new PondBird();
bird2 = new MountainBird();
bird1.color();
bird2.color();
}
}
Forex. see above code pallet for PondBird we call the default color method from the parent class because we are not overriding that method in PondBird class. But in MountainBird class, We are overriding that color method so, We get different behavior for Mountain Bird Class.
#java Main
yellow
Gray
Abstraction
Many objects hide their low-level details from the user so, A user could focus on their task instead of worrying about those details, forex. The airplane pilot may not know all the mechanical parts of the airplane but he can still fly it because of the controllers given to him, This hiding of details is called Abstraction.
See the following example of Abstraction, In java we can use abstract classes and interface to implement abstraction. here we are creating an interface for our Airplane.
interface AirplaneInterface {
public void takeOff();
public void makeAnnouncement();
public void activateAutopilot();
public void landOnAirport();
}
Pilot can only access this methods from his terminal ( for the sake of simplicity methods are kept less here).
Following is Concrete Airplane class which implements above interface.
class ConcreteAirplane implements AirplaneInterface {
public void takeOff() {
// complex logic
}
public void makeAnnouncement() {
// complex logic
}
public void activateAutopilot() {
// complex logic
}
public void landOnAirport() {
// complex logic
} /* hidden from user */
public void engineOptimization() {
// complex logic
}
public void connectToAirportCommunicationChannel() {
// complex logic
}
...
}
Since ConcreteAirplane class implements AirplaneInterface we can use the interface to only give user those methods and hide all other complex methods such as engineOptimization and connectToAirportCommunicationChannel.
Finally we create a reference of Interface and store the object of type ConcreteAirplane inside of it. And we get the desired output user cannot access methods other than those provided in interface which results in hiding complex logic from user.
class AirplaneTestDrive {
public static void main(String[] args) {
AirplaneInterface plane;
plane = new ConcreteAirplane();
plane.takeOff();
}
}
Encapsulation
Encapsulation is also known as data hiding, where we declare our instance variables as private and only give access to them via methods. Data encapsulation play’s a big role in the data validation part. Forex. If the velocity variable suddenly starts accepting a negative number because It is not encapsulated properly, then that would be a big problem for airplane monitoring. Encapsulation also combines related data and methods so that data and its related methods stay together as a logical unit.
In following diagram Data, Methods and class are encapsulated in one Unit and only methods associated with the data can access it.
See the following example on Encapsulation, Following code snippet validates velocity for negative numbers only and private is used to protect velocity variable to be accessed from outside of Class. data can only be accessed through the methods.
class AirplaneMonitoring {
private double velocity = 0;
public void setVelocity(double velocity) {
/* All validation goes here*/
if(velocity < 0) {
return;
}
// after validating assign the value
this.velocity = velocity;
}
public double getVelocity() {
return velocity;
}
}class AirplainMonitoringTestDrive {
public static void main(String[] args) {
AirplaneMonitoring airplaneMonitoring = new AirplaneMonitoring();
airplaneMonitoring.setVelocity(-1);
System.out.println(airplaneMonitoring.getVelocity()); // 0.0airplaneMonitoring.setVelocity(2.25);
System.out.println(airplaneMonitoring.getVelocity()); // 2.25
}
}
Conclusion
OOP helps us model real-world object into a programming construct, which in turn allow us to make a modular application which is extendable, reusable, and non-rigid in nature. In this blog, we have gone through basic building blocks that make any OO language a true OO language. In the end, this is a very vast topic so please consider this text as a tip of an iceberg and if you want to dwell deep in any OO language it is worth spending your time on this paradigm.