Please open the menu to show more

Monday, August 7, 2017

Frequently asked question asked by good companies on java programming language part-5

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 #
public class GreatGrandFather {
String name = "Prithvi Raj Kapoor";
}

# save this class inside GrandFather .java file #
public class GrandFather extends GreatGrandFather {
String name = "Raj Kapoor";
}



# save this class inside Father .java file #
public class Father extends GrandFather {
String name = "Rishi Kapoor";
}

# save this class inside Son.java file #
public class Son extends Father {
String name = "Ranbeer Kapoor";
void showNames() {
System.out.print("The name of GreatGrandFather is ");
// 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 ");
// access the variable of GrandFather
// here i am converting the type of Son's object to the GrandFather
System.out.println(((GrandFather)this).name);
System.out.print("The name of Father is ");
// access the variable of Father
// here i am converting the type of Son's object to the Father
System.out.println(((Father)this).name);
// note: we can also access the variable of class Father using "super"
       //  keyword, example "super.name"
System.out.print("The name of Son is ");
// access the variable of Son
// note: we can also access the variable of class Son using "this" keyword,
        // example "this.name"
System.out.println(((Son)this).name);
}
}

# save this class inside UseOfThisKeyword .java file #
public class UseOfThisKeyword {

public static void main(String[] args) {
// create object of class Son
        Son son = new Son();
// call the method using object-name "son" of class Son
        son.showNames();
}
}

2 comments:

  1. Didn't knew this technique before... Awesome sir !

    ReplyDelete
  2. These all will be helpful in interview,thanks to post this valuable questions.

    ReplyDelete