Get to know OOP concepts!

Get to know OOP concepts!

I've been recently looking through some requirements for internships/jobs and it caught my attention that a certain requirement keeps popping up "good knowledge of OOP concepts".

I studied object oriented programming through java a couple of years ago, actually implemented my knowledge on some college projects (fitness tracker, restaurant reservation system, fruit ninja clone) but two years seem like a long time ago, it almost feels like I forgot what I learnt.

cat-funny-cat.gif

So I decided to write this to go over my knowledge of OOP concepts and to benefit whoever wants to remember what they learnt like me or even interested to know about the topic!

What is object-oriented programming (OOP)?

Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior.

OOP focuses on the objects that developers want to manipulate rather than the logic required to manipulate them. This approach to programming is well-suited for programs that are large, complex and actively updated or maintained. This includes programs for manufacturing and design, as well as mobile applications.

What is the structure of object-oriented programming?

  • Classes are user-defined data types that act as the blueprint for individual objects, attributes and methods.

  • Objects are instances of a class created with specifically defined data. Objects can correspond to real-world objects or an abstract entity. When class is defined initially, the description is the only object that is defined.

  • Methods are functions that are defined inside a class that describe the behaviors of an object. Each method contained in class definitions starts with a reference to an instance object. Additionally, the subroutines contained in an object are called instance methods. Programmers use methods for reusability or keeping functionality encapsulated inside one object at a time.

  • Attributes are defined in the class template and represent the state of an object. Objects will have data stored in the attributes field. Class attributes belong to the class itself.

A simple example would be a class representing a person. The person class would contain attributes to represent information such as the person’s age, name, height, etc. The class definition might also contain functions such as "sayMyName" which would simply print that person’s name to the screen.

java-class-objects.jpg

A family could be constructed by instantiating person objects from the class for each member of the family. Each person object would contain different data attributes since each person is unique.

What are the main principles of OOP?

  • Encapsulation states that all important information is contained inside an object and only select information is exposed. The implementation and state of each object are privately held inside a defined class. Other objects do not have access to this class or the authority to make changes. They are only able to call a list of public functions or methods. This characteristic of data hiding provides greater program security and avoids unintended data corruption.

Add-a-subheading-1024x858.jpg

//A Java class which is a fully encapsulated class.  
//It has a private data member and getter and setter methods.  
package com.javatpoint;  
public class Student{  
//private data member  
private String name;  
//getter method for name  
public String getName(){  
return name;  
}  
//setter method for name  
public void setName(String name){  
this.name=name  
}  
}

let's break this down a little bit what are getters and setters? you might be wondering.

Getter and Setter are methods used to protect your data and make your code more secure. Getter returns the value, it returns the value of data type int, String, double, float. For the convenience of the program, getter starts with the word “get” followed by the variable name.

While Setter sets or updates the value. It sets the value for any variable which is used in the programs of a class. and starts with the word “set” followed by the variable name. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type. In both getter and setter, the first letter of the variable should be capital.

Words like, private and public are called access modifiers which we're going to talk about later.

Another thing you might be wondering about is the usage of the word this, it has been really confusing when I first learnt about it so let me try breaking it down to you a bit.

Usage of this keyword:

  • this can be used to refer current class instance variable.
  • this can be used to invoke current class method (implicitly).
  • this() can be used to invoke current class constructor.
  • this can be passed as an argument in the method call.
  • this can be passed as argument in the constructor call.
  • this can be used to return the current class instance from the method.

The scenario we are interested in now is the first one, to refer current class instance variable.

To understand it better, let's see an example with and without the usage of this keyword.

Without this:

class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
rollno=rollno;  
name=name;  
fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
class TestThis1{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}

Output would be:

0 null 0.0 0 null 0.0

With this:

class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
this.rollno=rollno;  
this.name=name;  
this.fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  

class TestThis2{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}

Output would be:

111 ankit 5000.0 112 sumit 6000.0

NOTE If local variables(formal arguments) and instance variables are different, there is no need to use this keyword, it's only required when local and instance variables are the same.

  • Abstraction ,objects only reveal internal mechanisms that are relevant for the use of other objects, hiding any unnecessary implementation code. The derived class can have its functionality extended. This concept can help developers more easily make additional changes or additions over time.

unnamed.png

abstract class Bike{  
  abstract void run();  
}  
class Honda4 extends Bike{  
void run(){System.out.println("running safely");}  
public static void main(String args[]){  
 Bike obj = new Honda4();  
 obj.run();  
}  
}

to break this down, Bike is an abstract class that contains only one abstract method run, its implementation is provided by the Honda class and the word extends is used with inheritance which is the next OOP principle we're going to discuss.

  • Inheritance, classes can reuse code from other classes. Relationships and subclasses between objects can be assigned, enabling developers to reuse common logic while still maintaining a unique hierarchy. This property of OOP forces a more thorough data analysis, reduces development time and ensures a higher level of accuracy.

Class_in_C__.png

class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

  • Polymorphism, objects are designed to share behaviors and they can take on more than one form. The program will determine which meaning or usage is necessary for each execution of that object from a parent class, reducing the need to duplicate code. A child class is then created, which extends the functionality of the parent class. Polymorphism allows different types of objects to pass through the same interface. In simple words, it means that an object can exist/behave in many forms.

polymorphism-in-C-Sharp.png

class Bike{  
  void run(){System.out.println("running");}  
}  
class Splendor extends Bike{  
  void run(){System.out.println("running safely with 60km");}  

  public static void main(String args[]){  
    Bike b = new Splendor();  
    b.run();  
  }  
}

In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, the subclass method is invoked at runtime, so the output would be running safely with 60km.

You can't deny that a certain word here caught your attentions and made you wonder what it means, overrides, so let's find out!

What is Overloading and Overriding?

When two or more methods in the same class have the same name but different parameters, it’s called Overloading.

When the method signature (name and parameters) are the same in the superclass and the child class, it’s called Overriding.

Overriding vs Overloading

  • Overriding implements Runtime Polymorphism whereas Overloading implements Compile time polymorphism.
  • The method Overriding occurs between superclass and subclass. Overloading occurs between the methods in the same class.
  • Overriding methods have the same signature i.e. same name and method arguments. Overloaded method names are the same but the parameters are different.
  • With Overloading, the method to call is determined at the compile-time. With overriding, the method call is determined at the runtime based on the object type.
  • If overriding breaks, it can cause serious issues in our program because the effect will be visible at runtime. Whereas if overloading breaks, the compile-time error will come and it’s easy to fix.

What are access modifiers?

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.

  • Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.

  • Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.

  • Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.

  • Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.

What are the benefits of OOP?

  • Modularity, when working with object-oriented programming languages, you know exactly where to look when something goes wrong. “Oh, the car object broke down? The problem must be in the Car class!” You don’t have to go line-by-line through all your code.

httpatomoreillycomsourceoreillyimages1529712.png

That’s the beauty of encapsulation. Objects are self-contained, and each bit of functionality does its own thing while leaving the other bits alone. Also, this modularity allows an IT team to work on multiple objects simultaneously while minimizing the chance that one person might duplicate someone else’s functionality.

  • Reusability, suppose that in addition to your Car object, one colleague needs a RaceCar object, and another needs a Limousine object. Everyone builds their objects separately but discover commonalities between them. In fact, each object is just a different kind of Car. This is where the inheritance technique saves time: Create one generic class (Car), and then define the subclasses (RaceCar and Limousine) that are to inherit the generic class’s traits.

1_lpxKjH6iJtqrYZgNE5oXIw.jpeg

Of course, Limousine and RaceCar still have their unique attributes and functions. If the RaceCar object needs a method to “fireAfterBurners” and the Limousine object requires a Chauffeur, each class could implement separate functions just for itself. However, because both classes inherit key aspects from the Car class, for example the “drive” or “fillUpGas” methods, your inheriting classes can simply reuse existing code instead of writing these functions all over again.

What if you want to make a change to all Car objects, regardless of type? This is another advantage of the OOP approach. Make a change to your Car class, and all car objects will simply inherit the new code.

  • Flexibility, suppose you now need just a few drivers, or functions, like “driveCar,” driveRaceCar” and “DriveLimousine.” RaceCarDrivers share some traits with LimousineDrivers, but other things, like RaceHelmets and BeverageSponsorships, are unique.

polymorphism-in-java-oop-concepts-in-java-what-is-object-oriented-programming.png

This is where object-oriented programming’s polymorphism comes into play. Because a single function can shape-shift to adapt to whichever class it’s in, you could create one function in the parent Car class called “drive” — not “driveCar” or “driveRaceCar,” but just “drive.” This one function would work with the RaceCarDriver, LimousineDriver and so on. In fact, you could even have “raceCar.drive(myRaceCarDriver)” or “limo.drive(myChauffeur).”

These are the basic concepts I was able to gather about object-oriented programming and these are the things that got me started, there are still tons of stuff to learn about it but this should be enough for brainstorming I think :')

I hope this is of help to anyone.