0
0
Javaprogramming~20 mins

Default methods in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Vehicle interface with a default method
Create an interface called Vehicle with a default method named describe() that returns the String "This is a vehicle."
Java
Need a hint?

Use the default keyword inside the interface to create a method with a body.

2
Create the Car class implementing Vehicle
Create a class called Car that implements the Vehicle interface. Do not override the describe() method.
Java
Need a hint?

Just declare the class and implement the interface. No need to write the describe method again.

3
Add the main method to create Car and call describe
Add a main method inside the Car class. Inside main, create an instance of Car named myCar and call myCar.describe(), storing the result in a variable called description.
Java
Need a hint?

Remember the syntax for the main method and how to create an object and call a method.

4
Print the description
Inside the main method of the Car class, add a line to print the description variable using System.out.println().
Java
Need a hint?

Use System.out.println(description); to print the text.