PSOOP_Lecture 06-2024-25
PSOOP_Lecture 06-2024-25
2
'this' Keyword uses
class Example {
int num;
Example(int num) {
this.num = num; // Using 'this' to differentiate between instance and
//local variable
}
void display() {
System.out.println("Number: " + num);
}
class Example {
void show() {
System.out.println("Inside show method");
}
void display() {
this.show(); // Using 'this' to call another method
}
class Example {
Example() {
this(10); // Calling another constructor
System.out.println("Default constructor");
}
Example(int num) {
System.out.println("Parameterized constructor: " + num);
}
class Example {
Example getInstance() {
return this; // Returning current class instance
}
void display() {
System.out.println("Method called using 'this'");
}
class Example {
void display(Example obj) {
System.out.println("Method called with 'this' reference");
}
void callMethod() {
display(this); // Passing current instance
}
class Example {
Example(Test obj) {
System.out.println("Constructor called with 'this' reference");
}
void callConstructor() {
new Test(this); // Passing current instance
}
class Parent {
private int privateVar = 10;
int defaultVar = 20;
protected int protectedVar = 30;
public int publicVar = 40;
}
class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
static void myPrint(int i) { Same name with different
System.out.println("int i = " + i); parameters
}
static void myPrint(double d) {
System.out.println("double d = " + d);
}
}
Method Overriding
• Useful if a derived class needs to have a different
implementation of a certain method from that of the superclass
• JVM (not the compiler) has to bind a method call to its implementation
• So the compiler doesn’t know its type, just knows its base type
class A
{ B
…
}
public class B extends A
{
…
}
Common Methods of Object Class
@Override
public int hashCode() {
return id * 31 + name.hashCode();
}