Java this and super keywords explained

𝙩𝙝𝙞𝙨 and 𝙨𝙪𝙥𝙚𝙧 keyword in java: 𝗣𝗼𝗶𝗻𝘁𝘀 𝘁𝗼 𝗿𝗲𝗺𝗲𝗺𝗯𝗲𝗿 In Java, 𝙩𝙝𝙞𝙨 and 𝙨𝙪𝙥𝙚𝙧 are reference keywords used to manage object behavior clearly and avoid ambiguity. => 𝙩𝙝𝙞𝙨 refers to the current object of the class.  • It is mainly used to differentiate instance variables(variables declared inside class) from local variables, call current class methods, and chain constructors using this(). 𝗞𝗲𝘆 𝗽𝗼𝗶𝗻𝘁𝘀:  • Refers to current class object  • Used to avoid variable shadowing  • Cannot be used in static context  • Supports constructor chaining 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝘤𝘭𝘢𝘴𝘴 𝘗𝘦𝘳𝘴𝘰𝘯 {   𝘚𝘵𝘳𝘪𝘯𝘨 𝘯𝘢𝘮𝘦;   𝘗𝘦𝘳𝘴𝘰𝘯(𝘚𝘵𝘳𝘪𝘯𝘨 𝘯𝘢𝘮𝘦) {     𝘵𝘩𝘪𝘴.𝘯𝘢𝘮𝘦 = 𝘯𝘢𝘮𝘦;   } } ===================================================== => 𝙨𝙪𝙥𝙚𝙧 refers to the parent class object.  • It is used in inheritance to access parent class variables, methods, and constructors. 𝗞𝗲𝘆 𝗽𝗼𝗶𝗻𝘁𝘀:  • Refers to immediate parent class  • Used during method overriding  • super() calls parent constructor  • Must be first statement in constructor 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝘤𝘭𝘢𝘴𝘴 𝘗𝘢𝘳𝘦𝘯𝘵 {   𝘪𝘯𝘵 𝘹 = 10; } 𝘤𝘭𝘢𝘴𝘴 𝘊𝘩𝘪𝘭𝘥 𝘦𝘹𝘵𝘦𝘯𝘥𝘴 𝘗𝘢𝘳𝘦𝘯𝘵 {   𝘪𝘯𝘵 𝘹 = 20;   𝘷𝘰𝘪𝘥 𝘴𝘩𝘰𝘸() {     𝘚𝘺𝘴𝘵𝘦𝘮.𝘰𝘶𝘵.𝘱𝘳𝘪𝘯𝘵𝘭𝘯(𝘹);    // 20     𝘚𝘺𝘴𝘵𝘦𝘮.𝘰𝘶𝘵.𝘱𝘳𝘪𝘯𝘵𝘭𝘯(𝘴𝘶𝘱𝘦𝘳.𝘹); // 10   } } 𝗤𝘂𝗶𝗰𝗸 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲:  • this → current class  • super → parent class  • this() → current constructor  • super() → parent constructor ✨ Follow for more 𝗝𝗮𝘃𝗮 & 𝗕𝗮𝗰𝗸𝗲𝗻𝗱 concepts! #Java #CoreJava #OOP #JavaInterview #BackendDevelopment #SpringBoot #SoftwareEngineering

To view or add a comment, sign in

Explore content categories