Dependency Injection in java with best example

Dependency Injection in java with the best example can be found here in this post. let’s discuss first, what is a dependency on object-oriented programming? if a java class uses an instance of another class, it is known as dependency between two classes. the object-oriented programmer should develop in such a way that every class is independent of each other.Dependency Injection in java with best example

Example:

Class ABC{

XYZ obj=new XYZ();  // creates instances of XYZ class with new operator 

}

class XYZ

{

}

ABC class contains the instance of XYZ class. it is an example of hard dependency.

Dependency injection is the best solution to fix the above dependency issue. what is dependency injection in java? object provider will be supplying the objects of another class. it allows the programmer to avoid hard code dependencies. Dependency Injection supports the dependency inversion principle.

public class abstractiondemo {
public static void main(String[] args) {
OperatingSystem winObj = new WindowsOperatingsystem(); // injector
Computer cmp = new Computer(winObj); // constructor dependency injection
cmp.operate();
}
}
class Computer { //high-level class
OperatingSystem OS;

public Computer(OperatingSystem OS) {
this.OS = OS;
}

void operate() {
OS.boot();
}
}
interface OperatingSystem{ // abstraction layer between Computer and WindowsOperatingsystem classes
void boot();
}
class WindowsOperatingsystem implements OperatingSystem{ //low level class
public void boot() {
System.out.println("windows is booting");
}
}

we are not creating the instance of another class in a low-level class. we are using an injector mechanism to pass dependent objects through the injector. Dependency Injection is provided by many frameworks like spring. we no need to create the object directly using a new operator but we will be using injectors to throw objects whenever it is needed.

abstraction plays a vital role in the dependency injection concept in object-oriented programming. it supports the open-closed principle, we can add additional changes without disturbing the existing code. it is quite a used topic in design patterns.

hope you have little understanding of Dependency Injection in java.


Posted

in

by

Tags:

Comments

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Design a site like this with WordPress.com
Get started