Java Reference
In-Depth Information
method(String... s1, int s2) : Not allowed
method(String... s1, String... s2) : Not allowed
method(String... s1, Dog... dogs) : Not allowed
method(String[] s1) : Allowed
method(String[] s1, String s2) : Allowed
method(String[] s1, String[] s2) : Allowed
method(String[] s1, String[] s2, Dog[] dogs) : Allowed
method(int i1, String[] s1, int i2) : Allowed
method(int i1, String[] s1, String... s2) : Allowed
method(int i1, String... s1, String[] s2) : Not allowed
You don't have to memorize this list (or these rules), as Eclipse will simply warn you when you
define a method incorrectly.
class methods
Just as you've seen for class variables, a class method , also denoted as a static method, is a method
that has been defined statically, meaning that this method is shared between all objects (instances)
belonging to the class. Again, as class methods belong to the class blueprint, it is not even necessary
to create objects to be able to use them.
I'll illustrate this concept with another example from the realm of pets. This time, let's define a Cat
class as follows:
class Cat {
static String preferredFood() {
return "Fish";
}
}
Note the static modifier in front of the method declaration is similar to what you've seen with static
variables. preferredFood is defined as a blueprint method, returning the preferred food for all cats.
Just as for instance methods, it is possible to call class methods through an object:
Cat myCat = new Cat();
System.out.println("A cat's preferred food is: "+myCat.preferredFood());
However, just as for class variables, this is not good practice, and Eclipse will warn you about such
behavior. Again, you should clearly indicate that you're accessing a static method by using the
class name, instead of the object variable:
System.out.println("A cat's preferred food is: "+Cat.preferredFood());
This also clearly illustrates that you do not have to create an object to use static methods.
 
Search WWH ::




Custom Search