Would this be the right place to use the java interface keyword?

I am new to Java. After simply reading the path discovery information, I read about using an empty class as " interface" for an unknown object type.

I am developing a game in Java based on a hospital theme. Until now, the user can create a reception and office GP. They are two different types of object, one - Buildingand one - ReceptionDesk. (In my class structure.)

My class structure is as follows:

GridObject-->Building
GridObject-->Item-->usableItem-->ReceptionDesk.

The problem arises when the useful element can be rotated, but the building cannot. The mouse click event is in the grid, so it calls the same method. The GP office is Buildingand the reception is ReceptionDesk. Only ReceptionDeskhas a method rotate. When right-clicking on a grid, if in build mode I have to use this "if" expression:

if (currentBuilding.getClass.equals(ReceptionDesk.getClass)

Then I need to create a new one ReceptionDesk, use the method rotate, and put the receptionist back in currentBuilding GridObject.

I'm not sure that I explain this question very well. I'm sorry. I am still new to Java. I will try to answer any questions, and I can post more code snippets if necessary. I did not know that there might be a problem with the fact that you do not know the class of the object, but I could also be wrong.

, , !:)

.

Rel

+3
3

, - . polymorphism. , . . , .

, , , , , . , , "", . "UsableItem" . , . ReceptionDesk UsableItem. UsableItem .

rotate() , - , AbstractUsableItem, , UsableItemand rotate(). , , , ReceptionDesk, rotate(). - :

UsableItem desk = new ReceptionDesk();
desk.rotate()

, , , , - ,

if (clickedObject instanceOf UsableItem) {
  ((UsableItem) clickedObject).rotate();
}

UsableItem . , , , .

+7

, , . , GridObject handleRightClick(), handleLeftClick() .. , " , GridObject, , , ".

, Building handleRightClick, ( ). ReceptionDesk handleRightClick, .

:

currentBuilding.handleRightClick(... any necessary parameters ...);
+3

, . - , , if(x instanceof Y) if(x.getClass().equals(Y.class)), .

, , , . - - , , . , , , - .

I must also warn you that an interface is not a completely empty class. There are some significant differences between empty abstract classes with abstract methods and interfaces. Instead of thinking of the interface as an empty class, think of the interface as a contract. By implementing the interface, your promises class to provide each of the methods listed in the interface.

+1
source

Source: https://habr.com/ru/post/1706210/


All Articles