Tuesday, 21 January 2014

Using super in java

how to use super keywords:constructors

super:

super has two general forms. The first calls the superclass’ constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass.


Using super to Call Superclass Constructors

A subclass can call a constructor defined by its superclass Using the super reference, we can access the (non-private) variables and methods of the superclass. One use of the super reference is to invoke the constructor of the superclass.

The Syntax for the super


super(arg-list);


Here, arg-list specifies any arguments needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass’ constructor.

Example for super

// uses super to initialize its attributes.
class BoxWeight extends Box  
{
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m)
 {
super(w, h, d); // call superclass constructor
weight = m;
}
}


Here super( ) was called with three arguments. Since constructors can be overloaded, super( ) can be called using any form defined by the superclass. The constructor executed will be the one that matches the arguments.


A Second Use for super


The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used.

The general form:

super.member

Here, member can be either a method or an instance variable.This second form of superis most applicable to situations in which member names of a subclass hide members by the same name in the superclass.

Example 2:Using super to overcome name hiding.


class A
 {
int i;
}
class B extends A // Create a subclass by extending class A
 {
int i; // this i hides the i in A
B(int a, int b)
{
super.i = a; // i in A
i = b; // i in B
}
void show()
 {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
 {
public static void main(String args[])
 {
B subOb = new B(1, 2);
subOb.show();
}

}


This program displays the following:

i in superclass: 1
i in subclass: 2

Although the instance variable i in B hides the i in A, super allows access to the i defined in the superclass. As you will see, super can also be used to call methods that are hidden by a subclass.



































1 comment :

  1. Nice examples and well explained
    redhat training in chennai | VMware training in chennai | linux training in chennai

    ReplyDelete