Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics/Interfaces and Tree Structures in Java

I am trying to create a tree structure (a binary tree) that is capable of holding two different types of class (a sphere and a rectangle).

For obvious reasons my sphere and rectangle will have different methods for getting their size (getSize()) and I also intend to have a constructor (for both classes) thats takes two objects (two spheres OR two rectangles) and combines them to create a larger sphere or rectangle.

How should I approach coding a node so that it can store either a sphere or a rectangle at a node calling the appropriate methods when required?

Would a simple interface accomplish this if i cast objects to the type i need?

Thanks,

DMcB

like image 825
DMcB1888 Avatar asked Jul 25 '26 14:07

DMcB1888


2 Answers

Would a simple interface accomplish this if i cast objects to the type i need?

An interface Shape would seem appropriate. If done right, you won't need a cast at all when inserting an item.

like image 163
Fred Foo Avatar answered Jul 27 '26 04:07

Fred Foo


I would create three classes. An abstract class Shape that contains all common code for rectangles and spheres.

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 left abstract such as getSize(), drawShape(), mergeShape(). Also, maybe not relevant but the Composite design pattern might be of good use for this problem

like image 40
GETah Avatar answered Jul 27 '26 03:07

GETah