0
0
Javaprogramming~20 mins

This keyword usage in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
This keyword usage
πŸ“– Scenario: Imagine you are creating a simple Java program to manage a book's details. You want to clearly understand how to use the this keyword to refer to the current object's properties.
🎯 Goal: You will build a Java class called Book with two properties: title and author. You will use the this keyword to set these properties inside the constructor and then print the book details.
πŸ“‹ What You'll Learn
Create a class called Book with two String properties: title and author
Create a constructor for Book that takes two parameters named title and author
Use the this keyword inside the constructor to assign the parameters to the class properties
Create a method called printDetails that prints the book's title and author
Create a main method to create a Book object and call printDetails
πŸ’‘ Why This Matters
🌍 Real World
Using <code>this</code> is common in Java when you want to clearly refer to the current object's properties, especially when parameter names match property names.
πŸ’Ό Career
Understanding <code>this</code> is essential for writing clear and bug-free Java classes, which is a fundamental skill for Java developers.
Progress0 / 4 steps
1
Create the Book class with properties
Create a public class called Book with two String properties named title and author.
Java
Need a hint?

Properties are variables inside the class but outside any method.

2
Add constructor using this keyword
Add a constructor to the Book class with parameters String title and String author. Use the this keyword to assign the parameters to the class properties title and author.
Java
Need a hint?

The this keyword helps to distinguish between the class property and the constructor parameter with the same name.

3
Add method to print book details
Add a public method called printDetails inside the Book class that prints the book's title and author using System.out.println. Use this.title and this.author to access the properties.
Java
Need a hint?

Use this to refer to the current object's properties inside methods.

4
Create main method and display book details
Add a main method inside the Book class. Inside main, create a Book object with title "Java Basics" and author "Alice". Then call the printDetails method on this object to display the book details.
Java
Need a hint?

The main method is the program's starting point. Create the object and call the method to see the output.