Calling method of same name from different class

前端 未结 2 1191
情歌与酒
情歌与酒 2021-01-13 15:32

I have some classes those have methods with same name. For example

public class People {
    private Long id;
    private String nm;
    private String nmBn;         


        
2条回答
  •  [愿得一人]
    2021-01-13 15:50

    First, you should create an interface with the common methods, let's call it Identifiable:

    public interface Identifiable {
    
        Long getId();
    
        String getNm();
    
        String getNmBn();
    }
    

    Ideally, you could make both People and Company implement this interface, but as you said you couldn't modify the existent Company and People classes, you'd then need to extend them, and make the subclasses implement the Identifiable interface:

    public PeopleExtended extends People implements Identifiable { }
    
    public CompanyExtended extends Company implements Identifiable { }
    

    Now, simply change the getCompanyString and getPeopleString methods to:

    public String getIdString(Identifiable id) {
        return id == null ?
               "" :
               id.getNmBn() + "|" + id.getNm() + "#" + id.getId();
    }
    

    And obviously, use the PeopleExtended and CompanyExtended subclasses.

提交回复
热议问题