B
B
BlobDead2015-10-29 20:17:04
Java
BlobDead, 2015-10-29 20:17:04

JAVA How to get a previously unknown class and its method?

Hello. Suppose I have a bunch of classes of different types, but implementing similar functionality, and now I need a class that would receive an instance of one of the already described class (which type is not known in advance) and could call its methods. What is better to use to implement such logic?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MiiNiPaa, 2015-10-29
@MiiNiPaa

Interfaces?
Create an interface that describes the functionality and let your classes implement it.

V
Vitaly Vitrenko, 2015-10-29
@Vestail

Let this bunch of similar classes implement one interface with the method you need. Then when you get an instance into a variable with an interface type, you can call the method you need, no matter what class it is. This is called polymorphism.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question