this keyword in Java

 

๐Ÿ”ท  this Keyword in Java

The this keyword is a reference to the current object — the object whose method or constructor is being called.

✅ Common Uses of this:


๐Ÿ”ธ 1. Distinguish instance variables from parameters


class Student { String name; // Constructor Student(String name) { this.name = name; // this.name refers to instance variable } void printName() { System.out.println("Name: " + this.name); } }

๐Ÿ”ธ 2. Call another constructor (Constructor Chaining)


class Book { String title; int pages; // Constructor with one parameter Book(String title) { this(title, 0); // Call another constructor } // Constructor with two parameters Book(String title, int pages) { this.title = title; this.pages = pages; } void display() { System.out.println(title + " - " + pages + " pages"); } }

๐Ÿ”ธ 3. Return current object


class Demo { Demo getObject() { return this; } }

Comments

Popular posts from this blog

Object Oriented Programming PBCST 304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Object Oriented Programming PBCST 304 Course Details and Syllabus

Type casting in Java