Methods Flashcards
What is the difference between a method and a function? Is there one?
A method, like a function, is a set of instructions that perform a task. The difference is that a method is associated with an object, while a function is not.
How do I designate a method’s inputs?
Put them in the parameters.
How do I designate a method’s outputs?
You just put them in the method signature instead of the word void.
Where can a method definition go in your source code? Can definitions be nested?
Where can a method call go in your source code? Can calls be nested?
How many things can a method return? (How many types?)
You can return only one value in Java. If needed you can return multiple values using array or an object. Methods can only return one type.
How do I return several things from a method?
What if I have nothing to return?
void keyword
How many return statements are allowed in a method?
You can have several, but it’s best to keep the code clean and clear.
What is the ideal length for a method?
5-10 lines
Can a method call itself?
Yes, when a method calls itself, it is called recursion.
What is the difference between a static and non-static method? Give an example of each.
Non-static methods have access to fields. Static methods don’t.
One way to think about it is that static methods are just independent methods with no context. They’re defined in a class, but they’re not part of an individual object.
Non-static methods can’t be executed independently. They’re part of an object. They have access to an object’s state.
Non-static methods are executed using an instance of an object. Static methods are executed using a class name.
Static method ex:
String.format
String.format(“Numbers: %s, %s, %s”, 1, 2, 3);
Non-static method ex: toUpperCase
String vegetable = “kale”;
vegetable.toUpperCase();
How do I indicate a method is non-static?
Omit the word static
Is this valid syntax?: void doNothing() { return; }
What is method overriding?
In addition to inheriting parent members, subclasses can completely replace a parent method. This is called overriding a method. To override, the method is re-implemented in the subclass