Hello all,
I've been learning
Java the last 3 weeks in my free time, I've got a strong background in JavaScript so while "things are kinda the same" they are "kinda different" as well. The syntax came naturally but I am now struggling with different ways of expressing an idea in a design.
I started a simple little project called "barnYard" and did the probably common exercise of creating a class called Animal with a few methods, etc. I then thought, well, an Animal belongs in a Barn, so let's make a barn class that holds an ArrayList of Animals[] etc... And then there are Farmers, etc...
Then in the true spirit of a tinkerer, I thought well, technically, Farmers and Animals are entities that can reside in a structure, so I rewrote things a little bit where I then had two classes, Actor and Structure, where Animal and Farmer extend Actor, and Barn extends Structure.
Now in JavaScript, the syntax is rather lenient where let's say I for whatever reason wanted to have a container/collection/array/WHATEVER of the following:
You get the idea, totally arbitrary objects that may or may not have anything in common. In the above example, doSomething is a method of Farmer (or maybe Actor, whatever).
Is there any similar design concept in Java? I know that all objects are a subclass of the class Object, but if I cast them (if that's even possible) as such in an ArrayList, how would I then know what they used to be without using instanceof or some other bad choice?
Should I think of making a class that encapsulates the arbitrary objects above, with some property that indicates what type of object they are? Something maybe like:
This way, as I construct Capsule objects, I can set a
String indicator (or Enum, whatever), indicating what type of Object is really contained. I could then express some logic in execution such as:
This seems like a roundabout way of accomplishing something that seems very easy in JavaScript. I realize they are two different languages, but they have similar roots. Any insight that anyone has would be appreciated.