D
D
Dmitry Krapivin2017-06-20 13:32:24
Java
Dmitry Krapivin, 2017-06-20 13:32:24

Can you give a simple example (code) of polymorphism in Java?

Polymorphism - allows us to work with different classes of objects using the same interface.
I can't understand how it works. Can you explain?
Example: we have a "Department" Interface, it has a "Count the number of employees" method. This interface is implemented by the "Workshop" and "Department" classes, which have the "Calculate the number of employees" methods.
Polymorphism means that if you need to call the method of the "Workshop" class, then another class, for example "Company", by referring to the "Department" interface and calling the "Calculate the number of employees" method, can call the method of the "Workshop" class.
Question: why refer to the interface, if you can refer directly to the "Workshop" class
Can you give an example of polymorphism in simple code, with your comments, please577cadeb3caa45e79539c4fea4c003a8.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Shockoway, 2017-06-20
@kiru

An interface is a list of methods, and if we abstract a little, then this is a certain behavior model, and when a class implements an interface, this means that it is guaranteed to support the behavior model described in the interface. Thus, if you have a certain set of different classes (in this case, Shop and Department), but supporting the same behavior model (Department interface), then this allows you to interact with it without looking at which specific class they belong to. belong.
There are many practical application scenarios, but here is the simplest one for you:
Let's say you have a task (taken from the ceiling) to calculate the daily cost of food for all employees of a particular unit. As a result, it turns out that we need a method that would take an instance of the unit as an argument and return a specific amount.

// Subdivision это тот самый интерфейс "Подразделение"
int getFoodCost(Subdivision subdivision) {
  // допустим, что на каждого человека тратится по 300 руб в день
  return subdivision.numberOfEmployers() * 300;
}

As a result, we get a method that can work with absolutely any class that implements the Subdivision interface. But if you didn’t use the interface, but simply added the numberOfEmployers() method to each class, then you would have to write your own version of getFoodCost() for each class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question