6
In this application we have the class Automóvel
:
public class Automovel {
private String marca;
private String matricula;
private String anoConstrucao;
private Motor motor;
private int preco = 0;
With their manufacturers, getters and setters.
And there’s a class called Motor
which is a class attribute Automovel
.
Class Motor
:
private int potencia;
public Motor() {}
public Motor(int potencia){
this.potencia = potencia;
}
public int getPotencia() {return this.potencia;}
public void setPotencia(int potencia) {
this.potencia = potencia
}
There are also 2 subclasses of this class (the MotorEletrico
and the MotorCombustão
):
public class MotorEletrico extends Motor {
private int autonomia;
public MotorEletrico() {}
public MotorEletrico(int potencia, int autonomia) {
super(potencia);
this.autonomia = autonomia;
}
public int getAutonomia() {
return autonomia;
}
public void setAutonomia(int autonomia) {
this.autonomia = autonomia;
}
}
And:
public class MotorCombustao extends Motor{
private int cilindrada;
private String combustivel;
public MotorCombustao(){}
public MotorCombustao(int potencia, int cilindrada, String combustivel){
super(potencia);
this.cilindrada = cilindrada;
this.combustivel = combustivel;
}
public int getCilindrada(){
return cilindrada;
}
public void setCilindrada(int cilindrada){
this.cilindrada = cilindrada;
}
public String getCombustivel(){
return combustivel;
}
public void setCombustivel(String combustivel){
this.combustivel = combustivel;
}
}
I store an automobile with a motorX in one array object Automovel
, but when I will try to access the getters and setters sub-class (MotorEletric
/Combustao
), only gets and sets of the mother class appear (Motor
).
My problem is I can’t access getters and setters of motor subclasses. Here is an example of what I tried:
Automovel arrayteste[] = new Automovel[49];
Motor motor1 = new MotorEletrico();
motor1.setPotencia(5);
Automovel automovel1 = new Automovel("Opel", "xx-12-xx", "2000", motor1, 2000);
arrayteste[0] = automovel1;
System.out.println(arrayteste[0].getMotor().getPotencia()); //Aqui, eu não consigo fazer o .getAutonomia
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.
– Maniero