Tuesday 23 January 2018

Super Keyword In Java


If a parent class and child class has same data members (variables) or member functions (methods).By default child class can access its own variables and methods. To access parent class methods and variables we have to use super keyword in child class.

Super is a keyword in java which refers to the immediate parent of a class.

Super is always declared in child class.

Only public and protected method can be called by super keyword.

Private method method can’t be called by super keyword.

Uses:
super is used in immediate parent class instance variable.

super is used to call or invoke immediate parent class method.

super () is used  to call or invoke immediate parent class constructor

Example:1
super is used in immediate parent class instance variable.

package result;
class LearningPoint92{ 

String name="Training"; 

class Demo extends LearningPoint92 { 

String name="Development";
int technology_used=15;

void display(){
System.out.println(super.name);//display name of LearningPoint92 class
System.out.println(name);//display name of Demo class 
System.out.println(technology_used); //display technology of Demo class
 } 
}

public class Result {

  public static void main(String[] args) {

 Demo d1=new Demo(); 
d1.display();
    }
   }
Output
Training
Development
15

Example:2
super is used to call or invoke immediate parent class method

package result;
class Square{ 
void display(int a)
        {
       System.out.println("square is:"+(a*a));    
        }
 } 

class Cube extends Square { 
 void display(int a){
super.display(5);      //call super class(square) method
System.out.println("cube is:"+a*a*a);   //call cube class method
}

public class Result {
  public static void main(String[] args) {
     Cube c1=new Cube(); 
      c1.display(6);
    }
   }
Output:
square is:25
cube is:216
Example:3
super () is used  to call or invoke immediate parent class constructor

package result;

class Square{ 

/*
 Square()
{
System.out.println("Default constructor Example:");
 */

Square(int a)     //parameterized  constructor
{
 System.out.println("square is:"+a*a);  
}
}

class Cube extends Square { 

Cube(int a)
 {

//super();-> call superclass default constructor

super(5);         //call superclass parameterized  constructor

System.out.println("cube is:"+a*a*a);     // print child class(cube) value
} 
}

public class Result {
 public static void main(String[] args) {
 Cube c1=new Cube(6); 
    }
   }
Output:
square is:25
cube is:216

No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...