Posts

Showing posts with the label this keyword

Java Interview Prep: Mastering this and super Keywords

Image
Understanding this and super in Java The this and super keywords are critical in object-oriented programming for managing references to the current class instance and its superclass. Here’s a breakdown of their usage, followed by potential interview questions to help in preparation. this Keyword The this keyword refers to the current instance of the class. Common Uses of this : Referencing Instance Variables: Resolves ambiguity when instance variables are shadowed by method or constructor parameters. class Person { String name; Person( String name) { this .name = name; // Resolves shadowing } } Calling Another Constructor in the Same Class: Allows constructor chaining within the same class. class Person { String name; int age; Person( String name) { this (name, 0 ); // Calls another constructor } Person( String name, int age) { this .name = name; this .age = age; } } Passing the Current Instance ...

Java this keyword - Example

The ' this ' keyword in Java is a keyword that can be used inside a class method or constructor. The 'this' keyword works as the reference to the current object, whose method or constructor is being invoked. You can use the 'this' keyword to reference any member of the current object inside an instance method or constructor. Following are the ways to use the ' this ' keyword in java: 1. Using ' this ' keyword to refer to current class instance variables 2. Using  this () to invoke the current class constructor 3. Using  ' this '  keyword to return the current class instance 4. Using  ' this '  keyword as a method parameter 5. Using  ' this '  keyword to invoke the current class method 6. Using  ' this '  keyword as an argument in the constructor call Using 'this' keyword to refer to current class instance variables //Java code for using 'this' keyword to //refer current class instance variables publ...