-3

Here is my code:

interface Dwelling {
int getNumberOfOccupants();
}

public class House extends Building implements Dwelling  {
@Override
public int getNumberOfOccupants() {
    return occupants;
}
}

public class ApartmentBuilding extends HighRise implements Dwelling{
@Override
    public int getNumberOfOccupants() {
        totalOccupants = numberOfFloors * occupantsPerFloor;
        return totalOccupants;
    }
 }



public class Village extends Building{
public int getPopulation(){
        size = House.getNumberOfOccupants() + ApartmentBuilding.getNumberOfOccupants();
        return size;
    }
 }

When I try to add the getNumberOfOccupants() methods from the House and ApartmentBuilding classes I am getting a Non-static method 'getNumberOfOccupants()' cannot be referenced from a static context error. I am not sure how I can add these methods to produce the getPopulation() method

  • 1
    Does this answer your question? [Non-static variable cannot be referenced from a static context](https://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – OH GOD SPIDERS Jul 29 '21 at 15:17
  • 2
    You can't, because those methods are not `static`. Nor should they be, as houses and other buildings vary in their key attributes, which are not particular to a class. Also your population method implementation (attempted) suggests you have a village with one house and one apartment - isn't that a bit strange? – g00se Jul 29 '21 at 15:18
  • ok sorry I am learning java and Im not sure how I would go about getting the total population for all buildings? – Delano Petrilli Jul 29 '21 at 15:20
  • 2
    `Village extends Building` does not make much sense. A Village isn't a more specific type of a Single Building. A Village is something that contains Buildings, but isn't a building itself. Your Village class should therefor not extend the building class, but be able to hold a List/Array of buildings that it is made of. – OH GOD SPIDERS Jul 29 '21 at 15:20
  • 2
    You need to think about your design more before writing code (the last thing). Think about it - what IS a village? – g00se Jul 29 '21 at 15:21

1 Answers1

1

you have created instance method getNumberOfOccupants() in the class House and same way in the class ApartmentBuilding. calling like these are static method, that's why you are getting error.