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 Printer
{
void printDocument(String doc)
{
System.out.println("Printing document: " + doc);
}
}
class OfficeWorker
{
void doWork()
{
Printer printer = new Printer(); // Dependency via local variable
printer.printDocument("ProjectReport.pdf");
System.out.println("Work completed.");
}
}
public class MainApp
{
public static void main(String[] args)
{
OfficeWorker worker = new OfficeWorker();
worker.doWork(); // OfficeWorker depends on Printer to print
}
}
Printing document: ProjectReport.pdf Work completed.
extends
keyword in case of classes.
implements
keyword in case of interfaces.
class Vehicle
{
void start()
{
System.out.println("Vehicle starts.");
}
}
class Car extends Vehicle
{
void drive()
{
System.out.println("Car drives.");
}
}
public class MainApp
{
public static void main(String[] args)
{
Car myCar = new Car();
myCar.start(); // inherited from Vehicle
myCar.drive(); // specific to Car
}
}
Vehicle starts. Car drives.
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.