W tej lekcji pokażę Ci czym jest przeciążanie metod. Zobaczysz co trzeba zrobić, żeby „przeciążyć” metodę i do czego nam to potrzebne.
Przeciążanie metod
Przeciążanie danej metody jest sytuacją, w której w tej samej klasie tworzymy kolejną metodę o tej samej nazwie ale różnych parametrach. Parametry mogą się różnić ilością (czyli jedna metoda jest bezparametrowa, a druga ma dwa parametry), typem (czyli jedna metoda przyjmuje jeden parametr int, a druga jeden parametr String) albo zarówno ilością jak i typem (Overloading Methods).
Po co nam przeciążanie metod?
Bez przeciążania metod pewnie spokojnie można by się obejść, ale lepiej sobie ułatwiać życie niż utrudniać. Dzięki przeciążaniu metod nie musimy stawać na rzęsach żeby np. tworzyć kolejne metody (i co gorsza wymyślać ich nazwy), które będą robiły to samo (lub prawie to samo) ale na podstawie innych parametrów. Na przykładzie naszego kodu zamiast tworzyć metodę info() oraz infoWithMessage(String message), możemy po prostu stworzyć info() oraz info(String message).
Kod
PlanetTests.java
package Przeciążanie; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class PlanetTests { @Test public void info_NoParametersProvided_ReturnsFullInfo(){ Planet mars = new Planet("Mars", 1.026, 6787, 2, false); Assertions.assertEquals("Name: Mars\n" + "Rotation period (days): 1.026\n" + "Diameter (km): 6787\n" + "Moons: 2\n" + "Has rings?: false", mars.info()); } @Test public void info_MessageProvided_ReturnsFullInfo(){ Planet mars = new Planet("Mars", 1.026, 6787, 2, false); String message = "This is the favourite one!"; Assertions.assertEquals("Name: Mars\n" + "Rotation period (days): 1.026\n" + "Diameter (km): 6787\n" + "Moons: 2\n" + "Has rings?: false" + "\n\n" + message, mars.info(message)); } }
Planet.java
package Przeciążanie; public class Planet{ private String name; private double rotationPeriodInDays; private int diameter; private int numberOfMoons; private boolean hasRings; public Planet(String name, double rotationPeriodInDays, int diameter, int numberOfMoons, boolean hasRings) { this.name = name; this.rotationPeriodInDays = rotationPeriodInDays; this.diameter = diameter; this.numberOfMoons = numberOfMoons; this.hasRings = hasRings; } public Planet(String name) { this.name = name; } public String info(){ return ("Name: " + name + "\nRotation period (days): " + rotationPeriodInDays + "\nDiameter (km): " + diameter + "\nMoons: " + numberOfMoons + "\nHas rings?: " + hasRings); } public String info(String message){ return ("Name: " + name + "\nRotation period (days): " + rotationPeriodInDays + "\nDiameter (km): " + diameter + "\nMoons: " + numberOfMoons + "\nHas rings?: " + hasRings + "\n\n" + message); } }