1
I’m starting in the Java language and I ran into a problem. The following is as follows: I have 1 class that calls Vehicle, it has the attribute mark(string) and has 3 classes that inherit it, in this case they are: Car(qtdPortas int), Moto(qtdCilindradas int), Boat(potMotor int) and I will have a vector[] to store the inserted vehicles, my problem is as follows, How do I insert into the vector[] an object of the type Car, or Bike, or Boat, specifically? I had thought about the following code, but it only serves to insert normal values, when there is no inheritance, as the code would be to insert in an array when there is 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;
}
Put more relevant code for us to analyze. We need to know right to hierarchy, as stated
vetor
, where it will be used in this code. It is not very clear what you want, what you mean by "how do I insert into the vector[] an object of the type Car, or Bike, or Boat, specifically?". An example of how it will be inserted would be nice.– Maniero
Good morning bigown! I added a model of the classes to facilitate understanding. From code, the only thing I’ve done so far is to create classes, attributes, constructor and getter and Setter methods. I was going to start doing the "inserts" method, but I’ve come across the question of how to insert values in a vector when there is inheritance. In this case, when the "user" is inserting a new Car, it is necessary to use the getter and Setter of the Car+Vehicle class, the same for when it is a Bike or a Boat, understand?
– Gabriel Queiroz
Already helped, but still can not know what you need, what your difficulty. Actually I’m not seeing any problem. But it can be because there is no context of what you are doing. A method played like this does not indicate much for us to help.
– Maniero
As I am learning, there is still no problem because I could not begin to do. My first task in these systems is to create a method to insert into the vector vehicles of type Car, Bike and Boat, I need to create the code that makes this insertion in the vector. While I was learning, I was able to create a code that inserts into an array[] simple values, for example, the user enters a number and he writes to the array, now I need to create the code, to insert values into an array, but they are not so simple values, there is an inheritance, and with it the system must use the attributes of the chosen class
– Gabriel Queiroz
That’s the problem, you don’t have a problem so you can’t even explain what you want. It seems to me that your code already does what you want. Maybe not, but I have no way of knowing why you refuse to provide information that helps solve the problem.
– Maniero