I'm new to java and am running into the error
An enclosing instance that contains ... is required
when creating a new object from a subclass defined in the same source file as its parent, but not when the subclass has its own source file, and I'd like to understand why.
The main file:
package tessty
public class Tessty {
public static void main(String[] args) {
Person me = new Person();
me.addtoitems();
}
}
Another source file for the "Person" class:
package tessty;
import tessty.Item.*; // I included this import as per NetBeans' suggestions
public class Person {
Item[] items;
public Person() {
items = new Item[3];
}
public void addtoitems() {
items[0] = new Apple(); // Compile error thrown here
items[1] = new Shoe(); // and here
items[2] = new Hat(); // but not here
}
}
The "Item" class source file with two sub-classes defined in the same file:
package tessty;
public class Item {
int weight;
public class Apple extends Item {
public Apple() {
weight = 2;
}
}
public class Shoe extends Item {
public Shoe() {
weight = 3;
}
}
}
And finally, another child of Item, but defined in its own source file:
package tessty;
public class Hat extends Item {
public Hat() {
weight = 1;
}
}
I'd really like to be able to define sub-classes in the same file as the parent class for organizational purposes (the application I'm working on will have many "small" sub-classes). Could someone please explain why I'm getting this error only for the sub-classes that are in the same source file as their parents? Is it related to the fact I have to use an import for the sub-classes in the same file as their parent and not for the sub-class with its own file?