Did you know an object can have a function “attached” to it. In fact, any object can have lots of functions attached to it. Even more exciting, all objects that are of the same type (i.e. were built from the same class) all have the same functions attached to them.
A function attached to an object is called a “method” and it has two differences from a normal function:
This lifts object from mere custom-compound-data to something more, something profound…. objects! All right, we already called them objects, but things with lots of data fields and lots of functions all bundled up together are so incredibly useful they have become the basis of most programming in the 21st century. We really don’t do much with boring old ‘int’ or ‘char’ values, we are much more likely to use some object, after all - it has methods attached!
There were methods just waiting for us already, on the
String objects we have been using.
Because every object built from the same class have the same methods, the class definition is the perfect place to describe them.
Thanks to a feature of Java we will learn later there are some methods that “come for free” in every class (and thus are attached to every object). A few of these are interesting to us: