Java – getter from a object attribute Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java – getter from a object attribute without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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:


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?


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{

    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.

We are here to answer your question about Java – getter from a object attribute - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji