To check if two shapes are touching in Java, you can use the intersects
method of the Shape
class. This method takes another Shape
object as an argument and returns true
if the two shapes intersect (touch), and false
if they do not.
For example, consider the following code, which checks if a rectangle and a circle are touching:
Rectangle rect = new Rectangle(10, 10, 50, 50); Circle circle = new Circle(30, 30, 25); if (rect.intersects(circle)) { System.out.println("The shapes are touching"); } else { System.out.println("The shapes are not touching"); }
In this example, the rectangle and the circle are touching, so the output will be "The shapes are touching".
Note that the intersects
method only checks if the shapes intersect in a 2D plane. If you want to check if the shapes are touching in 3D space, you may need to use a different approach.