Showing posts with label super. Show all posts
Showing posts with label super. Show all posts

Sunday, 15 May 2011

Explicit call to super class constructor in java

Normally, you don't explicitly write the constructor for your parent class, but there are two cases where this is necessary:

 

Passing parameters

You want to call a parent constructor which has parameters (the default construct has no parameters). For example, if you are defining a subclass of JFrame you might do the following.

class Chairman extends Employee {
. . .
//======== constructor
public Chairman(String name_,String designation_) {
super(name_);
This was shown here.

No parameterless constructor in parent


There is no parent constructor with no parameters. Sometimes is doesn't make sense to create an object without supplying parameters.

Referring to base class members using super in java

Referring to base class from derived class, can be done with the help of super. Here super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form:

super.member


Here, member can be either a method or an instance variable.
class A {

int i;
}

// Create a subclass by extending class A.
class B extends 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);
}

}

Calling base class constructor using super in java

In java, we use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.

Usage

super(parameter-list);

Example

//X is super class, with attributes width, height, depth and has constructor for 3 attributes.

class Y extends X {
double weight; // weight of box // initialize width, height, and depth using super()

Y(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}