Question: How can we access the variables of super-classes without using "super" keyword.
Answer: We can access the variables of super-classes using "this" keyword instead of "super" keyword.
Lets understand how following code words =>
As we know the "this" keyword denotes current object in java programming language. And the type of any object can be type caste to any of its super-classes using the following syntax
==> ((name-of-superclass)this)
after this syntax we can access the variable of super-classess like given syntax
==> ((name-of-superclass)this).variable-name
note: before using this code please create a "Java Project" in "Eclipse"
# save this class inside GreatGrandFather .java file #
Lets understand how following code words =>
As we know the "this" keyword denotes current object in java programming language. And the type of any object can be type caste to any of its super-classes using the following syntax
==> ((name-of-superclass)this)
after this syntax we can access the variable of super-classess like given syntax
==> ((name-of-superclass)this).variable-name
note: before using this code please create a "Java Project" in "Eclipse"
# save this class inside GreatGrandFather .java file #
public class GreatGrandFather {
String name = "Prithvi Raj Kapoor";
}
# save this class inside GrandFather .java file #
String name = "Raj Kapoor";
}
# save this class inside Father .java file #
String name = "Rishi Kapoor";
}
# save this class inside Son.java file #
String name = "Ranbeer Kapoor";
void showNames() {
System.out.print("The name of GreatGrandFather is ");
// access the variable of GreatGrandFather
// access the variable of GreatGrandFather
// here i am converting the type of Son's object to the GreatGrandFather
System.out.println(((GreatGrandFather)this).name);
System.out.print("The name of GrandFather is ");
// here i am converting the type of Son's object to the GrandFather
System.out.print("The name of Father is ");
// here i am converting the type of Son's object to the Father
// note: we can also access the variable of class Father using "super"
// keyword, example "super.name"
// keyword, example "super.name"
System.out.print("The name of Son is ");
// note: we can also access the variable of class Son using "this" keyword,
// example "this.name"
// example "this.name"
System.out.println(((Son)this).name);
}
}
# save this class inside UseOfThisKeyword .java file #
public static void main(String[] args) {
// create object of class Son
Son son = new Son();
Son son = new Son();
// call the method using object-name "son" of class Son
son.showNames();
son.showNames();
}
}
Didn't knew this technique before... Awesome sir !
ReplyDeleteThese all will be helpful in interview,thanks to post this valuable questions.
ReplyDelete