Methods and Encapsulation Flashcards
Order of method declaration components
1) Access Modifier (public, private, etc.)
2) Optional Specifier (final, static, etc.)
3) Return type
4) Method name
5) Parameter list
6) Optional Exception list (throws blahblah)
7) Method body
What does the public access modifier mean?
The method can be called from any class.
What does the private access modifier mean?
The method can only be called from within the same class.
What does the protected access modifier mean?
The method can only be called from classes in the same package or subclasses.
What is the default level of access for a method?
The method can only be called from classes in the same package.
If you are using a vararg parameter, where must it go?
At the end of the list of parameters
When you omit a vararg parameter from your method call, what does it pass by defualt?
An empty array
What can you pass in as a vararg parameter?
Either an array or a comma separated list of items (that will then be converted to an array) (or null)
If a method or variable is static, what does it mean?
It’s shared by the whole class basically, so you can call it like ClassName.method() or ClassName.var rather than needing a separate instance of the class. You can also use an instance of the variable to access static things, you just don’t have to. If you set that instance to null, it will still work when accessing static things!
Can static methods refer to non-static methods and variables?
NO
However a non-static method or variable can reference a static method or variable
How do we name static final variables?
All caps with underscores between words
How can you make all variables declared in a block of code static?
static {
int var1 = 1;
int var2 = 2;
}
When does the static initializer run?
When the class is first used
Static Imports
Used to import static members of classes so that you don’t have to precede the method o variable name with the class name
import static java.util.Arrays.asList;
Is Java pass-by-value or pass-by-reference and what does that mean?
It is a pass-by-value language, meaning with primitives a copy of the variable is made and the method receives that copy, so that changes made to the variable passed in are not actually being made to the original value passed in. Rather than passing it the actual reference to the variable, it’s merely using the literal value of it.
With objects however, that copy is still pointing to the same object so the changes will take effect as long as it’s just methods being called on them instead of pointing them to new objects. For example,
StringBuilder s = new StringBuilder(); changeString(s);
void changeString(StringBuilder sb) { sb.append("hello"); // makes change sb = "howdy"; // Doesn't make change }