Generic / interface and tree structure in Java
I'm trying to create a tree structure (binary tree) that can accommodate two different types of classes (a sphere and a rectangle)
For obvious reasons, my sphere and rectangle will have different methods to get their size (getSize ()), and I plan to have a constructor (for two classes). They need two objects (two spheres or two rectangles) and combine them to create a larger sphere or rectangle
How should I handle node coding so that it can store spheres or rectangles on the node and call the appropriate methods when needed?
If I convert the object to the type I need, will a simple interface implement this?
thank you,
DMCB
Solution
I will create three classes
public abstract class Shape{
// contains all common code related to shapes
// such as child elements
Shape parentNode; // This will help navigate up
List<Shape> children; // This will help navigate down the tree
// Define,merge,split methods which are common to all shapes
// define shape specific methods
}
public class Rectangle : Shape{
// Implement shape's abstract methods for this class
}
public class Sphere : Shape{
// Implement shape's abstract methods for this class
}
All shape specific methods should be abstract, such as getsize(), drawshape(), mergeshape() In addition, it may not be relevant, but the composite design pattern may solve this problem well
