Home > other >  Does anyone know why in java you can create a class with two methods with the same name and that are
Does anyone know why in java you can create a class with two methods with the same name and that are

Time:10-18

I would like to understand the following syntax:

Especially the two methods that have the same name and that return the name of the class

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MovieDto implements Serializable {

private static final long serialVersionUID = 1L;

private Integer idMovie;
private String nombre;
private String sinopsis;

public Movie toEntity(){
  Movie entity = Movie.builder()
        .idMovie(getIdMovie())
        .nombre(getNombre())
        .sinopsis(getSinopsis())
        .build();
    return entity;
}



public MovieDto fromEntity(Movie entity) {

    return fromEntity(entity, this);
}


public MovieDto fromEntity(Movie entity, MovieDto template) {

    setIdMovie(entity.getIdMovie());
    setNombre(entity.getNombre());
    setSinopsis(entity.getSinopsis());

    return this;
}

How can you create two methods with the same name and the same type of the class?

   public MovieDto fromEntity(Movie entity){
    return fromEntity(entity, this);
   }

   public MovieDto fromEntity(Movie entity, MovieDto template) {

    setIdMovie(entity.getIdMovie());
    setNombre(entity.getNombre());
    setSinopsis(entity.getSinopsis());

    return this;
}

CodePudding user response:

This is method overloading. In java, two or more methods can have the same name with different parameters.

CodePudding user response:

At the class file level, the 'name' of a method actually includes its erased parameter types and erased return type. In other words, that second fromEntity method you have there? Its named fromEntity(Lcom/foo/torres/movies/Movie;Lcom/foo/torres/movies/MovieDto;)Lcom/foo/torres/movies/MovieDto;

You can use javap to see that in action.

javac just sees you call fromEntity(someExpression, someOtherExpression) and will go on a bit of a 'resolution' goosechase: It tries to figure out which of the many different methods whose simple name is fromEntity you actually intended to call. This can be complicated, but the java language specification has a long section dedicated to exactly how the compiler does this. Once the compiler knows which one you meant, it simply puts the 'full name' of that method in the class file. The JVM (which runs class files) thus has an easy time of it.

  • Related