D4 - Inner Classes, Static/Dynamic binding

Software, Java

Inner Classes

Inner classes in java are mainly seprated to static and non-static ones. If an inner class is static, it behave like any other outer class, it just happens to be inside an outer class. It doesn't require an instance of the outer class to be initiated. A benefit of such case may be the possibility of using the outer class private methods.

On the other hand, non-static classes are legit inner classes that depends on an instance of the outer class. Those cases are used when we want to allow a class to exists only within another class. For example: inner class room inside an outer class house. There must be an instance of a house for a room to exists. Thus, we restrict creation of rooms in a logically correct way.

Static/Dynamic binding

This is a subject related to inheritance and function calling through instances of classes. If a class is inherited by another, the use of methods/fields from each of the classes is decided in certain way. Overall, one can consider that the methods which will be called are the subclass's methods (this is called Dynamic binding and happens in runtime). However: fields and static/private/final methods are Staticly Bound and require additional observation. They will usually run through the class of the pointer (this is called static binding). A small example to clarify:

class Organism{
    public String pubFunc(){return "Organism public function";}
    public static String statFunc(){return "Organism static function";}
}
class Human extends Organism{
    public String pubFunc(){return "Human public function";}
    public static String statFunc(){return "Human static function";}
}
public static void main(String[] args) {
    Organism oh = new Human();
    System.out.println(oh.pubFunc());
    System.out.println(oh.statFunc());

Output:

Human public function
Organism static function

2 important notes:

  • If the pointer is of the same class as the instance, there is only one class to call methods from.
  • In this section we're talking about overridden methods, as methods with with unique names don't intersect with others, and the only method that exists will be called.

Good day!

RwK