Object-Oriented Programming provides lots of ideas like Polymorphism, Abstraction, Inheritance, Encapsulations, etc. Today there are lots of Object-Oriented Programming languages are Java, C++, Python, PHP, C#, etc. The main motive of any Object-Oriented Programming language is to represent the real-world entity. Firstly, we need to understand more carefully what is an object and what is the class.
OOPs Concepts in Java
Class in Java
Class is nothing but collections of objects. It helps us to create a blueprint for a particular object. Moreover, it does not consume memory.
It represents a set of properties or methods that are common to all objects of one type. In general, the class declarations can include the following components, in order.
- Modifiers: A class can have by default the default access.
- Class name: The name should begin with an initial letter (capitalized by convention).
- Superclass(if any): The name of the class’s parent (superclass), if any, preceded by a keyword extends. A class can only extend (subclass) one parent.
- Interfaces(if any): It is the comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. The class can implement more than one interface. Through Interface, we can implement multiple inheritance.
Object in Java
As mentioned above, an Object is a real-world entity such as a chair, table, pen, pencil, etc. It has both state and behavior and be physical or logical. I consume space. An object consists of :
- State: It is represented by attributes of the object. The state reflects the properties of an object.
- Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.
- Identity: It gives the unique name to an object and enables one object to interact with other objects.
Method in Java
A method is the collection of statements that perform some specific task and return the result to a caller. A method can perform some specific task without returning anything. Methods allow us to reuse code without retyping the code. In Java, every method must be part of some class that is different from other languages like C, C++, and Python. Methods are time savers and help us to reuse code without retyping the code.
Method Declaration
In general, method declarations have six components which are the following.
- Modifier-: Defines access type of the method i.e. from where it can be accessed in your application. In Java, there are 4 types of access specifiers.
- public: It is accessible in all classes in your application.
- protected: It is accessible within the class in which it is defined and in its subclass(es)
- private: It is accessible only within the class in which it is defined.
- default (declared/defined without using any modifier): It is accessible within the same class and package within which its class is defined.
- The return type: The data type of the value returned by the method or void if does not return the value.
- Method Name: The rules for field names apply to method names as well, but the convention is a little different.
- Parameter list: Comma-separated list of the input parameters is defined, preceded with their data type, within the unclosed parenthesis. If there are no arguments, you must use the empty parentheses ().
- Exception list: The exceptions you expect by a method can throw, you can specify these exception(s).
OOPs in Java
There are four main OOP concepts in Java Programming Language. These are Inheritance, Polymorphism, Encapsulation, and Abstraction. Now we are going to discuss it one by one.
Inheritance in Java
Whenever an object inherits any property from another class, then it is known as Inheritance.
We use inheritance to increase the reusability of any program. Suppose if we are working on a big project using Java and there are lots of classes and among these classes, we have methods. Now there a situation occurs where we need to use the same method again that has been declared before some classes. Now to reduce the memory of the program, we use Inheritance.
Let’s understand inheritance with the help of an example.
// Inheritance.java //creating mammal class as parent class class Mammal { void Identity() { System.out.println("It is a Mammal class"); } } //exteding parent class class Man extends Mammal { void Category() { System.out.println("It is a Man class which extends Mammal"); } } class Inheritance { public static void main(String []er) { Man m =new Man(); //accessing parent class method using child class object instance m.Identity(); //accessing chile class method m.Category(); } }
See the below output.
Polymorphism in Java
Polymorphism is the ability of the object to take on many forms.
In Java, we use method overriding and method overloading to achieve polymorphism.
Now the question is, what is Method overriding?
It is a concept of OOP where the method of a child class can inherit the method of its parent class. It allows using one method in different ways depending on the object of child class or parent class.
Method Overloading is also a concept of Polymorphism where a single method can perfume different tasks depending on the context in which it’s called. It works in a different context for these we need to pass the different arguments to it.
// Poly.java //method overloading class Test { //method with two arguments int add(int a,int b) { return (a+b); } //method with three arguments int add(int a, int b, int c) { return (a+b+c); } } class Poly { public static void main(String []er) { Test t= new Test(); System.out.println(t.add(1,2));//method with two argument will be calling System.out.println(t.add(1,2,3));//method with three argument will be calling } }
See the below output. It is an example of Method Overloading in Java.
Now, let’s write the program of Method Overriding in Java.
// Poly.java class Vehicle { public void move() { System.out.println("It moves"); } } class Bike extends Vehicle { //overriding the method of its parent class public void move() { System.out.println("Bike moves and accelerates"); } } class Poly2 { public static void main(String[] er) { Vehicle v=new Vehicle(); //invoking parent class mehtod v.move(); v=new Bike(); //invoking child class method v.move(); } }
See the below output of Method Overriding.
Abstraction in Java
In OOP, Java is one of the most powerful concepts. Abstraction means to represent code in a sophisticated way so that it lets avoids repeating the same data.
Suppose, there is a method that is used to calculate average marks in a different class, and that method is also used in another class, due to this requirement we use Abstraction. We achieve abstraction using the Abstract method and interface in Java.
In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using Java Interfaces.
Let’s see an example to understand this Abstract better way. See the following code.
// Abstraction.java //creating abstract class abstract class Mark { // abstract method abstract int avgMarks(int n); } //extending abstract class class CSE extends Mark { int avgMarks(int n) { return n; } } //extending abstract class class ME extends Mark { // decaring abstract method int avgMarks(int a) { return a; } } //driver class class Abstraction { public static void main(String []er) { CSE c=new CSE(); System.out.println(c.avgMarks(90)); ME m=new ME(); System.out.println(m.avgMarks(80)); } }
See the following output.
Encapsulation in Java
Encapsulation is another one of the essential concepts in OOP. It is also considered the most powerful concept. It helps users to keep their data private from the user. To make private the data entered by the user, we have a setter method and to fetch the private data to show the user we have a getter method.
Let’s take an example to understand it better way. See the following code of encapsulation.
// Encap.java class ATMCard { private int pin; void setPin(int pin) { this.pin=pin; } int getPin() { return pin; } } class Encap { public static void main(String []er) { ATMCard c=new ATMCard(); c.setPin(1234); System.out.println(c.getPin()); } }
See the below output.
Best Practices for OOP Concepts in Java
- DRY (Don’t Repeat Yourself). It is the core concept of OOP Language. You should never have two blocks of identical code in two different places. Instead, you can have one method you use that method for different applications.
- If you expect your Java code to change in the future, encapsulate it by making all the variables and methods private at the outset. As code changes, increase access to “protected” as needed, but not too public. It is bad practice to turn all your code to the public.
- Single Responsibility. Another best practice for writing applications in Java is the Single Responsibility Principle. A class should always have only one functionality, it can’t be responsible for more than one task. That way, it can be called and/or extended on its own when new uses arise for it, without causing the coupling between different functionalities.
- Open Closed Design. Make all the methods and classes closed for modification but open for the extension. That way, your tried and tested code can remain static but can be modified further to perform as new tasks are added in the future.
That’s it for this tutorial.