Login    New User    Forgot Password    Help      

This and Super keywords

Java Tutorials

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’ssuper class.

The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.

Example

// Inheritance
// SUPER
class base
{
int a;
int b;
             
        base()
        {
        a=10;
        b=20;
        }

        void showdata()
        {
        System.out.println("Value of a is "+a);
        System.out.println("Value of b is "+b);
        }

}

class drive extends base
{
// new decleartion of same variable as of class s
int a;
int b;

     drive()
     {
     // super acts somewhat like this except that it always refers
     // to the super class of the sub class
     a=super.b;
     b=super.a;
     }

     void show()
     {
     System.out.println("Value of a is "+a);
     System.out.println("Value of b is "+b);
     System.out.println("\nAgain calling values of base class\n");
     System.out.println("Value of a is "+super.a);
     System.out.println("Value of b is "+super.b);

     }

}

class herit3
{
public static void main(String args[])
{
base b1=new base();
b1.showdata();

drive ob=new drive();
ob.show();

}
}

Output

Java Tutorials