Wednesday, May 14, 2008

Usage of the keyword super


Accessing Superclass Members: If a subclass has overridden certain method of a superclass then ‘super’ keyword is used to call the superclass method from within any method of the subclass. By default, it’ll call the subclass method only. For example:-

public class Superclass {
public void commonMethod(){
//…implementation of the method
}
}

Suppose this class is extended by a class named ‘Subclass’ and that subclass overrides the definition of the ‘commonMethod’ then ‘super’ will be used to call the Superclass-version of this method inside the subclass.

public class Subclass extends Superclass{
……
public void commonMethod(){
Super.commonMethod(); //superclass version called
……
}

public void anotherMethod(){
commonMethod(); //subclass version called
……

}
}

Inside Subclass Constructors: By default, super() is added as the first line of any subclass constructor which doesn’t explicitly call any superclass constructor as its first line. This is the reason why a superclass without the default constructor will cause an exception to be thrown if its subclasses don’t call any of the superclass constructors as the first line of their implementation. In that case, the compiler automatically inserts ‘super()’ as the first line and throws an exception after not finding any default constructor in the sperclass. (If you add explicit constructors to a class, don’t forget to add the default constructor as well because the compiler doesn’t provide that automatically in that case)

class superclass{
public superclass(){
//…implementation
}
public superclass(int i){
//… implementation
}
}

class subclass extends superclass{
public subclass(int p){
super(); // auto added if no superclass cons called
//… implementation
}

public subclass(int p, int q){
super(p); // it should be the first line
//…implementation
}
}




Share/Save/Bookmark


2 comments:

Ravi Kumar Gupta said...

This is really a gre888 innovative idea by GEEK Explains. It contains lots of necessary basic information abt the subject, which is really helpful for everyone....

Thanks a lots GEEK...

Geek said...

Thanks for the appreciation Ravi. I honestly believe that it's only half done without contribution (which will be equally useful for everyone) from all our visitors including you :-)

Keep visiting/posting!


~Geek