Doubt about polymorphism

Asked

Viewed 49 times

0

Hello, good afternoon, I have a question related to polymorphism.

Suppose I have an object Casa implementing Imovel where Imovel has a method getValorIptu() and House has an attribute nomeProprietario.

I would like to have a method that only calculates the total value of the IPTUS of a Property List and tbm a method that applies, or calculates, a tax to a property.

Why can’t I send a list of homes to a method that accepts a property listing? And, since I can’t have you do what I said in the question above, because I can send a house to a method that accepts a property?

I tried to use more or less the logic that exists when making a method that accepts a List<?> and he also accepts a ArrayList pq the same implements List. Likewise, Casa implements Imovel but makes a mistake.

Is there any other way?

The intention is that I can create a method that is punctual in what it will use, in the case of the method that receives a list, it would only use the getValorIptu() and would not need nomeProprietario

In the image below is the test code I did, but I still did not understand

inserir a descrição da imagem aqui

1 answer

0

Marcos, getting a hook in what other colleagues have already commented on what you could do is convert your List of Houses on a List of Immovable.

Example:

public static void main(String[] args) {
    
    Casa c = new Casa();    
    List<Imovel> lm = new ArrayList<>();        
    lm.add(c);              
    Main.aplicarVariosImpostos(lm);     

}

static void aplicarVariosImpostos(List<Imovel> testList) {      
    for (Imovel i: testList) {
        System.out.println(i.getValorIptu()); 
    }
}   

Browser other questions tagged

You are not signed in. Login or sign up in order to post.