I have created a basic inheritance program using a polymorphic array. From the parent-class, this array is looped through and each object (created from the child-class) at each index executes the parent-class’ instance method.
As an experiment, I created an object within the child-class’ constructor of its’ parent-class type, and executed the parent-class’ instance method from there.
For reasons unknown to me, this is causing the instance method (executed from the child-class’ constructor) to execute the number of times as the length of the parent-class’ polymorphic array (if the polymorphic array has 5 elements, the child-class’ method call will be executed 5 times).
Here is the parent-class:
public class MyClass
{
// instance variables
protected String name;
protected String numStrings;
// constructor
public MyClass(String name)
{
this.name = name;
}
// instance method
public void getDescription()
{
System.out.println("The " + name + " has " + numStrings + " strings.");
}
// main method
public static void main(String[] args)
{
MyClass[] instruments = new MyClass[2];
instruments[0] = new Child("Ibanez bass guitar");
instruments[1] = new Child("Warwick fretless bass guitar");
for(int i = 0, len = instruments.length; i < len; i++)
{
instruments[i].getDescription();
}
} // end of main method
} // end of class MyClass
…here is the child-class:
public class Child extends MyClass
{
// constructor
public Child(String name)
{
super(name); // calling the parent-class' constructor
super.numStrings = "four";
MyClass obj = new MyClass("asdf");
obj.getDescription();
}
} // end of class Child
…and here is the output:
The asdf has null strings.
The asdf has null strings.
The Ibanez bass guitar has four strings.
The Warwick fretless bass guitar has four strings.
The problematic line is this:
if you just simply call getDescription() instead of obj.getDescription(), it should be OK. Since ‘Child’ extends ‘MyClass’ the super constructor call is for initializing everything in the super class (let’s just say you can imagine it for now as an implicit
new MyClass("...")) you don’t have to instantiate ‘MyClass’ explicitly.