class Address
{
String city = "Delhi";
String country = "India";
void displayAddress()
{
System.out.println("City: " + city + ", Country: " + country);
}
}
class Student
{
String name = "Deepak";
int rollno = 101;
// Direct reference to another class
Address address = new Address(); // Object created directly inside the class
void displayInfo()
{
System.out.println("Name: " + name + ", Roll No: " + rollno);
address.displayAddress();
}
}
public class MainApp
{
public static void main(String[] args)
{
Student student = new Student(); // No need to pass Address
student.displayInfo(); // Displays student info along with address
}
}
Name: Deepak, Roll No: 101 City: Delhi, Country: India
class Engine
{
void startEngine()
{
System.out.println("Engine starts.");
}
}
class Car
{
// HAS-A relationship: Car has an Engine
private Engine engine;
// Constructor Injection: Engine is provided from outside
Car(Engine engine)
{
this.engine = engine;
}
void startCar()
{
engine.startEngine(); // Car uses Engine to start
System.out.println("Car starts.");
}
}
public class MainApp
{
public static void main(String[] args)
{
// create the dependency
Engine engine = new Engine();
// inject it into Car
Car myCar = new Car(engine);
myCar.startCar();
}
}
Engine starts. Car starts.
class Processor
{
void startProcessor()
{
System.out.println("Processor starts processing.");
}
}
class Laptop
{
// HAS-A relationship: Laptop has a Processor
private Processor processor;
// Setter Injection: Injecting dependency through setter method
public void setProcessor(Processor processor)
{
this.processor = processor;
}
void startLaptop()
{
processor.startProcessor();
System.out.println("Laptop starts.");
}
}
public class MainApp
{
public static void main(String[] args)
{
// Create the dependency
Processor processor = new Processor();
// Create the dependent object
Laptop myLaptop = new Laptop();
// Inject the dependency using setter
myLaptop.setProcessor(processor);
// Use the dependent object
myLaptop.startLaptop();
}
}
Processor starts processing. Laptop starts.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.