0
0
Javaprogramming~30 mins

Why interfaces are used in Java - See It in Action

Choose your learning style9 modes available
Why interfaces are used
πŸ“– Scenario: Imagine you are building a simple system where different types of devices can be turned on and off. Each device behaves differently, but they all share the ability to be switched on or off.
🎯 Goal: You will create an interface to define the common behavior of turning devices on and off, then implement this interface in different device classes. This will show why interfaces are useful to ensure different classes share the same behavior.
πŸ“‹ What You'll Learn
Create an interface called Switchable with two methods: turnOn() and turnOff()
Create a class called Light that implements Switchable
Create a class called Fan that implements Switchable
In the main method, create objects of Light and Fan and call their turnOn() and turnOff() methods
πŸ’‘ Why This Matters
🌍 Real World
Interfaces are used in software to ensure different parts follow the same rules, like how different devices can be controlled similarly.
πŸ’Ό Career
Understanding interfaces is important for writing clean, reusable code and working with many Java frameworks and APIs.
Progress0 / 4 steps
1
Create the Switchable interface
Create an interface called Switchable with two methods: void turnOn() and void turnOff().
Java
Need a hint?

An interface defines methods without bodies. Use interface keyword and declare methods without implementation.

2
Create the Light class implementing Switchable
Create a class called Light that implements the Switchable interface. Implement the methods turnOn() and turnOff() to print "Light is ON" and "Light is OFF" respectively.
Java
Need a hint?

Use implements Switchable after the class name. Provide method bodies that print the required messages.

3
Create the Fan class implementing Switchable
Create a class called Fan that implements the Switchable interface. Implement the methods turnOn() and turnOff() to print "Fan is ON" and "Fan is OFF" respectively.
Java
Need a hint?

Similar to Light, implement Fan with the required print statements.

4
Create the Main class and test the devices
Create a class called Main with a main method. Inside main, create objects of Light and Fan. Call their turnOn() and turnOff() methods to show the output.
Java
Need a hint?

Create objects and call the methods to see the messages printed.