I am working with these classes:
class Klant
public class Klant {
private String naam;
private String adres;
private String geboortedatum;
private double gewicht;
private int bmi;
private Abbonement abbonement;
public Klant(String naam, String adres, String geboortedatum, double gewicht, int bmi, Abbonement abbonement){
this.naam = naam;
this.adres = adres;
this.geboortedatum = geboortedatum;
this.gewicht = gewicht;
this.bmi = bmi;
this.abbonement = abbonement;
}
public Abbonement getAbbonement() {
return abbonement;
}
}
class Abbonement
public abstract class Abbonement {
private String begindatum;
private int contractduur;
private double maandprijs;
Abbonement(String begindatum, int contractduur, double maandprijs){
this.begindatum = begindatum;
this.contractduur = contractduur;
this.maandprijs = maandprijs;
}
}
class Milon
public class Milon extends Abbonement{
private int niveau;
public Milon(String begindatum, int contractduur, double maandprijs, int niveau){
super(begindatum, contractduur, maandprijs);
if(niveau >= 1 && niveau <= 25) {
this.niveau = niveau;
} else {
this.niveau = 1;
}
}
public int getNiveau() {
return niveau;
}
}
Now I have a Klant
object with a Milon
subscription. At the moment I am stuck retrieving the niveau of their subscription.
First thought was:
piet.getAbbonement().getNiveau()
But it isn't working probably because it is from a abstract class I think?
Now my question is how can I return niveau from Milon
if it's abbonement in a Klant
object?
You could try something similar to this:
Abbonement abbonement;
int niveau;
abbonement = myKlant.getAbbonement();
if (abbonement instanceof Milon) {
Milon milon;
milon = (Milon)abbonement;
niveau = milon.getNiveau();
} else {
niveau = 0;
}
If the property is quite general, which seems to be the case, bring it to the base class.
public abstract class Abbonement {
public int getNiveau() {
return 0;
}
...
public class Milon extends Abbonement{
@Override
public int getNiveau() {
return niveau;
}
}
Normally one would have a method in the base class, overridden in Milon to do something with niveau
and possibly other fields. Say for displaying info on the Abbonement. Or something condensing the business logic Abonnement.isGoedNiveau()
.
Casting Abbonement to Milon is more a pragmatic hack, and smells of bad style: at that place extra info is too concrete.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.