How to store values in a vector using inheritance / polymorphism?

0

I'm starting in the Java language and I came across a problem. It is the following: I have 1 class that calls Vehicle, it has the attribute tag (string) and has 3 classes that inherit it, in the case are: Car (qtdPort int), Moto (qtdCilindradas int), Boat (potMotor int) and I will have a vector [] to store the inserted vehicles, my problem is the following, how do I insert into the vector [] an object of the type Car, or Moto, or Boat, specifically? I have thought of the following code, but it is only used to insert normal values, when there is no inheritance, what would the code look like to insert into a vector when there is an inheritance?

public void insereVeiculo(Veiculo veiculo)
    {
        int contador = 0;
        for (int i = 0; i < this.vetVeiculo.length; i++) 
        {
            if(this.vetVeiculo[i] == null)
                break;
            else
                contador++;
        }
        this.vetVeiculo[contador] = veiculo;        
    }

    
asked by anonymous 23.05.2017 / 17:11

3 answers

1

If the intention is to limit by subtype through an object of the supertype, I believe that a simple check with instanceof would already solve:

public void insereVeiculo(Veiculo veiculo)
{
        int contador = 0;
        for (int i = 0; i < this.vetVeiculo.length; i++) 
        {
            if(this.vetVeiculo[i] == null)
                break;
            else
                contador++;
        }

        if(veiculo instanceof Carro) {   
            this.vetVeiculo[contador] = veiculo;        
        }
}
    
23.05.2017 / 20:06
2

If what you wanted was really the answer that was accepted then the most correct would be:

public void insere(Carro carro) {
    int contador = 0;
    for (carro : vetVeiculo) {
        if(caro == null) break;
        contador++;
    }
    vetVeiculo[contador] = carro;        
}

I placed it on GitHub for future reference .

In fact this loop is awful, even though I have improved, and inefficiency is huge. Because I do not know the context and can not help it anymore.

If you still want to do it the wrong way, at least make it a bit more efficient:

public void insereVeiculo(Veiculo veiculo) {
    if (veiculo instanceof Carro) {
        int contador = 0;
        for (carro : vetVeiculo) {
            if(caro == null) break;
            contador++;
        }
        this.vetVeiculo[contador] = veiculo;
    }
}
    
24.05.2017 / 17:49
-1

You will create an object vector.

Objects[] vetors = new Objects [] {Carro,Moto, Barco};

In the method of each subclass you implement the addVeiculo() by placing the object in the vector.

    
23.05.2017 / 19:45