Use of static keyword

Quick question on clarification. In the examples of using objects, objects are always declared using "class" and not "static class". However, if you declare an object without the "static" keyword, you cannot define any class variables or methods. If you do use the "static" keyword, the behaviour of the object does not appear to change, however you can declare object variables and methods.

So, my question is, why not always use the "static" keyword to declare classes? Is there an optimisation loss in using it? It seems to just add the ability to use object variables and methods.


  • edited October 2017

    ... objects are always declared using "class" and not "static class".

    • A small pedantic correction: Classes & interfaces aren't exactly objects.
    • Rather they're object makers or constructors when we call them via keyword new.
    • We also use classes & interfaces for declaring a variable's datatype.
    • B/c when we create classes & interfaces, we're also creating datatypes.
  • edited October 2017 Answer ✓

    ... why not always use the static keyword to declare classes?

    • In Java, only nested classes can be declared w/ the static keyword.
    • Top classes, on the other hand, are always implicitly static already.
    • Inside ".pde" tab files, all classes & interfaces are nested, not top.
    • And when a nested class isn't declared w/ static, they're also called inner.
    • Inner classes have direct access to all members of their enclosing classes.
    • Inside ".pde" tab files, the top enclosing class for all nested classes & interfaces is a PApplet subclass.
    • That's the reason we can still directly access all PApplet's API even inside our own inner classes, like ellipse() or mouseX for example.
    • However, if we declare a nested class w/ static, that class is restricted to access PApplet's static members only.
    • A static nested class behaves pretty much like top classes.
    • Therefore, like top classes, a static nested class needs to request a PApplet reference in order to access its non-static members as well.
  • Thanks! That information is not really evident from the references.

Sign In or Register to comment.