Using Default Methods in Java Interfaces
π Scenario: Imagine you are building a simple system for different types of vehicles. Each vehicle can describe itself. You want to provide a common description method that all vehicles can use, but also allow each vehicle to add its own details.
π― Goal: You will create an interface with a default method that provides a basic description. Then, you will create a class that implements this interface and uses the default method. Finally, you will print the description of the vehicle.
π What You'll Learn
Create an interface called
Vehicle with a default method describe() that returns a String.The default
describe() method should return the String "This is a vehicle."Create a class called
Car that implements the Vehicle interface.In the
Car class, do not override the describe() method.Create a
main method to create an instance of Car and print the result of calling describe().π‘ Why This Matters
π Real World
Default methods allow adding new functionality to interfaces without breaking existing code. This is useful when evolving APIs or libraries.
πΌ Career
Understanding default methods is important for Java developers to maintain and extend interfaces safely in large projects.
Progress0 / 4 steps