Skip to content

Q 33 - this keyword #38

Discussion options

You must be logged in to vote

🎯 Uses of this in Java

Here’s where this really shines:

1. Referencing Instance Variables

If a method has parameters with the same name as instance variables, this clears up the confusion.

class Student {
    int age;
    Student(int age) {
        this.age = age; // 'this.age' refers to the instance variable
    }
}

2. Calling Other Constructors

Used to call another constructor in the same class.

class Book {
    String title;
    int pages;
    Book(String title) {
        this(title, 0); // Calls the second constructor
    }
    Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }
}

3. Passing Current Object

You can pass the current object as an…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by AmjustGettingStarted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants