0

I want to calculate a person's BMI by passing an instance of that person as parameter in class BMI static method calculate() as follows:

Main.java

public class Main {
    public static void main(String[] args) {
        John john = new John(182, 68);
        BMI.calculate(john); // NaN???
    }
}

Physique.java

public interface Physique {
    int height = 0;
    int weight = 0;
}

John.java (implements Physique interface)

public class John implements Physique {
    int height;
    int weight;
    int age;

    public John(int height, int weight, int age) {
        this.weight = weight;
        this.height = height;
    }

}

BMI.java

public class BMI {

    public static void calculate(Physique physique) { // problem?
        System.out.println(physique.height / Math.pow(physique.weight, 2));
    }
}

I figure the problem should be my misuse of interface as type in paramater in BMI class. It works if I use calculate(John john), but if I have another person, that won't work. How could I correctly implement this?

William Le
  • 825
  • 1
  • 9
  • 16
  • 2
    Your problem is your interface's properties `int width` and `int height`, this seem to be getting "defaulted" over `John`s implementation - in fact, they don't even make up part of the interface's over all required - try removing `height` and `width` from `John`, the compiler won't compiler about non-compliance with the interface. Instead, define two methods, `getWidth` and `getHeight` both which return `int` – MadProgrammer Jun 02 '23 at 02:30
  • 1
    You might also want to read [Attributes / member variables in interfaces?](https://stackoverflow.com/questions/7311274/attributes-member-variables-in-interfaces) – MadProgrammer Jun 02 '23 at 02:31
  • @MadProgrammer thank you very much, I just solved the problem thanks to your suggestion. It seems I need encapsulation over ```height``` and ```weight``` – William Le Jun 02 '23 at 02:39

0 Answers0