Home Java Java-tips Oop Constructors Constructors - super example

Ask Questions?

View Latest Questions

Advertisement


 
 

Constructors - super example
Posted on: July 26, 2006 at 12:00 AM
Example of class without parameterless constructor.

Java Notes

Constructors - super example

Example of class without parameterless constructor

In this tutorial we will show you how to use the Constructors in details.

Example code provided here will help you in learning the Java Constructors easily.

While creating a class if any constructor is defined then compiler does not automatically create a default parameter less constructor.

In a class you can define any number of constructors having different parameters. These types of constructor is used when you have to create the object of class with different parameters.

 

In the following java class Parent.java we are declaring a constructor which takes int as an argument.

Then we showed the use of this.

Here is the complete example code.

 

/////////////////// class without a parameterless constructor.
//  If any constructor is defined, the compiler doesn't
//  automatically create a default parameterless constructor.
class Parent {
    int _x;
    Parent(int x) {   // constructor
        _x = x;
    }
}

////////////////// class that must call super in constructor
class Child extends Parent {
    int _y;
    Child(int y) {  // WRONG, needs explicit call to super.
        super(0);
        _y = y;    
    }
}

In the example above, there is no explicit call to a constructor in the first line of constructor, so the compiler will insert a call to the parameterless constructor of the parent, but there is no parameterless parent constructor! Therefore this produces a compilation error. The problem can be fixed by changing the Child class.

////////////////// class that must call super in constructor
class Child extends Parent {
    int _y;
    Child(int y) {  // WRONG, needs explicit call to super.
        _y = y;    
    }
}

Or the Parent class can define a parameterless constructor.

/////////////////// class without a parameterless constructor.
//  If any constructor is defined, the compiler doesn't
//  automatically create a default parameterless constructor.
class Parent {
    int _x;
    Parent(int x) {   // constructor with parameter
        _x = x;
    }
    
    Parent() {        // constructor without parameters
        _x = 0;
    }
}

A better way to define the parameterless constructor is to call the parameterized constructor so that any changes that are made only have to be made in one constructor.

    Parent() {        // constructor without parameters
        this(0);
    }
}

Note that each of these constructors implicitly calls the parameterless constructor for its parent class, etc, until the Object class is finally reached.

Copyleft 2003 Fred Swartz MIT License, Last update: 2003-05-05
Advertisement


DMCA.com