Answer the question
In order to leave comments, you need to log in
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, please
Answer the question
In order to leave comments, you need to log in
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;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question