Java: Methods - OOP

Static methods

If your method doesn't use an object of the class it is defined in, but does some work only on it's parameters, then you can declare the method to be static. Except for some utility methods and main(...), you should probably not be using static methods. A good example of a static methods in Java is the Math or Character classes. For example, the Math.cos(x) method calls the cosine method in the Math class. Cosine takes only one (primitive) parameter, and it doesn't work on any object. Make a call to a static method by putting a class name and a dot in front of the method call.

Signature

The signature of a method is its name and types of its parameters. The signature is used to select which method is to be called in a class. When you define more than one method by the same name in a class, there must be a difference in the number or types of the parameters. When there is more than one method with the same name, that name is overloaded.

Overriding

You override a method when you define a method that has the same name as in a parent class. A good example of this is when you define a JApplet you write an init() method. The JApplet class already has an init() method which you are overriding. When the browser calls init(), it will then call your version of the method. In this case you need to write init() because the init() in JApplet does nothing. Similarly, JPanel's paintComponent() method is overridden when you declare a JPanel for drawing.

All calls go to your new method, and not to the method by the same name in the parent class. To call the method in the parent class, as you must do in the first line of paintComponent(), prefix the call with super..

Overloading

A method name is overloaded when there are two or more methods by the same name in a class. At first it sounds like overloading methods would produce a lot of confusion, but it really reduces the confusion.

You can also define a method in one class that has the same signature (name and parameters) as the method in a different class. This is not called overloading, and there can be no confusion because the object in front of the method identifies which class the method is in.