Sunday 25 March 2018

"this" & "super" keyword in java

"this keyword"


"this" is a keyword in java.

'this' keyword refers to the object of the current class.

It is used to access the instance member of the current class in a method of the class.

It is a pointer variable.



Example of this keyword



class ThisDemo

     int rollno; 
     String name; 
     float fee; 
     Student(int rollno,String name,float fee)

    { 
       rollno=rollno; 
       name=name; 
      fee=fee; 
     } 
     void display(){System.out.println(rollno+" "+name+" "+fee);} 

class TestThis1


       public static void main(String args[])

      { 
          Student s1=new Student(111,"ankit",5000f); 
          Student s2=new Student(112,"sumit",6000f); 
          s1.display(); 
          s2.display(); 
      }

}
 

"Super keyword" 



The super keyword is a reference variable which is used to refer immediate parent class object.  

Usage of super keyword

1. To call the constructor of super class.
2. To access the member of the super class.

Example of super keyword


class Animal
{  
    String color="white";  
}  
class Dog extends Animal
{  
    String color="black";  
    void printColor()
   {  
        System.out.println(color);
        System.out.println(super.color);
    }  
}  
class TestSuper1
{  
      public static void main(String args[])
     {  
      Dog d=new Dog();  
      d.printColor();
      }




Popular posts