Q:

How to create a method that governs all subclasses in Java

In Java I'm creating a class called Room. Room is further divided into two types of rooms: a subclass called largeRoom and a subclass called smallRoom. I'm trying to write a mostExpensive() method that will tell me which room was the mostExpensive() to build. 
I know that if smallRoom and largeRoom were instances of Room it would be easy: I would simply declare the method as static. However I'm not sure how to achieve this same effect with subclasses. Any help would be appreciated!
Thanks 

A:

Being static or not have no direct link to super and sub classes.
static members are members which belongs to the class and not a specific object.
For creating room class, you can do something like this:
class Room{  //can be declared as abstract
    int cost;
    public int getCost(){return cost;}
}

class largeRoom extends Room{
    //inherit cost from Room class
}

class smallRoom extends Room{
    //inherit cost from Room class    
}

write a mostExpensive() method that will tell me which room was the mostExpensive() to build.

This method needs to compare a collection of Room objects, thus unlikely that you will be creating this method within the Room classes itself.
If you used an ArrayList to store the collection of Rooms.
public Room mostExpensive(ArrayList<Room> allRooms)
{
    Room mostExpensiveRoom;  
    int max = 0;
    for(int x=0; x<allRooms.size(); x++)
        if(allRooms.get(x).getCost() > max){
            mostExpensiveRoom = allRooms.get(x);
            max = allRooms.get(x).getCost();}
    return  mostExpensiveRoom;
}

This shows how you can make use of the mostExpensive() method.
public static void main(String[] args){
    List<Room> allRooms = new ArrayList<Room>();
    allRooms.add(new smallRoom());
    allRooms.add(new largeRoom());

    Room mostExpensiveRoom = mostExpensive(allRooms);
}

If you do not want to iterate through the collection manually searching for the most expensive room, you may let Room class implement comparable and sort your room collection then get the first/last record from the sorted collection. I doubt you will do that, but that is one alternative.

