Week 4 - Methods
Methods¶
Method Signature¶
- Access Modifer (public, protected, private),
- Optional [static] modifier,
- Return Type (void, double, String, Object, etc)
- Method Name (Anything you want following nameing convention)
- Method Parameters (Comma separated list of DataType parameterName)
- Method Name (Anything you want following nameing convention)
- Return Type (void, double, String, Object, etc)
- Optional [static] modifier,
Static/Class Method¶
First Let’s Re-Visit Static¶
- In the Student class below remember you can declare static variables, which are variables that won’t vary with instances of a class.
1 2 3 4 5 6 7 |
|
- Storing variables statically is more memory efficient because we don’t have separate storage locations for institution and semester per student.
- Because static means class-level we only allocate memory for these variables once when the class is loaded.
-
Static is largely used for efficient memory mangagment in Java.
-
Example of a static or class method (i.e. belongs to the class)
1 2 3 4 5
public class MyClass { public static void main(String args[]) { // Method block statments go here... } }
-
Every instance of the class has access to the static/class method.
- If ANY instance of the class modifies the static variable, its modified for ALL Instances
- Static methods can access static/class variables without an object instance.
- Only static data can be accessed.
- All static variables and methods are stored in the Heap when a class is loaded, but the Addresses are shared.
- Prior to Java 8, there used to be a static/non-heap memory location called the Method Area or PermGen where they were stored, but this is no longer used.
- A new area of Heap called MetaSpace is now used where all the names fields of the class, methods of a class with the byte code of methods, constant pool, JIT optimizations are stored.
Static Instance Counter | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
- This is a mental picture, of Instance methods, but in reality a single memory location is used and the Object pointer is passed to it.
Object Instance Counter 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
public class InstanceCounter { private static int numInstances = 0; protected static int getCount() { return numInstances; } private void addInstance() { numInstances++; } InstanceCounter() { this.addInstance(); } public static void main(String[] arguments) { System.out.println("Starting with " + InstanceCounter.getCount() + " instances"); for (int i = 0; i < 500; ++i) { new InstanceCounter(); } System.out.println("Created " + InstanceCounter.getCount() + " instances"); } }
Public/Object/Instance Method¶
-
Example of a public or object/instance method (i.e. can only be called from an object instance)
1 2 3 4 5
public class MyClass { public String sayHello(String firstName, String lastName) { return "Hello %s %s!".format(firstName, lastName); } }
-
Does NOT contain static keyword.
- Requires an Object Instance to call.
- Belong to the Object of the class, not to the class
- Are NOT stored on a per-instance basis, even with virtual methods (CIS-18 will talk about these).
- They’re stored in a single memory location, and they only know which object they belong to because the Object’s pointer is passed when you call them.
- They can be overridden since they are resolved using dynamic binding (binding method to method body/declaration) at run time.
Calling Methods¶
Calling a Static/Class Method¶
- Example calling the static/class method
1
MyClass.main(new String[]);
Calling an Object/Instance Method¶
- Example calling the public/object/instance method
1 2
MyClass myClass = new MyClass(); myClass.sayHello("Trevor", "Hartman");
Scope¶
Static Variable / Method Scope¶
- You can NOT declare static variables in
main(String[] args)
or any other method. - Static variables/methods must be declared as class members, since the belong to the class.
- Static variables/methods can be accessed by calling the class name, no instance needed.
- Static variables/methods can be called from static OR non-static methods.
Non-Static / Instance Method Scope¶
- Can only be accessed by first creating an instance of the class.
- Trying to access a non-static variable from a static method is an error.
Error Example | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Example of Proper Access | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
What do we use Methods for?¶
- Reuseable Code!
- i.e. don’t have to rewrite System.out.println from scratch every time we want to print to console.
- Parameterize Code
- Allow us to provide a parameters that changes the way the code works.
- Top-Down Programming
- Solve big problems by breaking it down into smaller parts (i.e. methods)
- Smaller Conceptual Units (Cleaner Code)
- Makes it easier to debug and maintain the code over-time if methods are concise and well-named.
- Abstraction
- Methods hide local variables and implementation from rest of code, simplifying other parts of the program.
When to use Static Methods¶
-
Static Methods criteria for use
- static methods can’t modify the state of an object.
- 4 wheels of a car, but all 4 are independent or have independent state.
- static methods mostly operate on arguments passed into it, commonly Utility Methods.
- java.lang.Math or StringUtils both only really perform action on arguments.
- StringUtils.isEmpty(String text)
- if you need a method to act on the entire class hierarchy
- equals() method for Ojbects is a good example
- static methods can’t modify the state of an object.
-
Other Examples of Static Methods
- Factory design pattern (i.e. a method to CREATE other objects)
- Utility methods like Array (provides methods that only work on array arguments)
- valueOf functions that convert types
-
Every other type of method should be a public/object/instance method
Method Parameters¶
- Parameters are values given to a method that can be used in its execution.
- The parameters of a method are defined on the uppermost line of the method within the parentheses following its name.
- The values of the parameters that the method can use are copied from the argument values given to the method when it is executed.
Example Parameterized Method | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Excercises¶
- Create a method called printText which prints the phrase “In a hole in the ground there lived a method” and a newline.
Exercise 1
1 2 3 4 5 6 7 8 9 |
|
- The code below contains a method that has been named with an incorrect style.
1 2 3
public static void printcodingis_cool() { System.out.println("Coding is cool!"); }
Exercise 2
1 2 |
|
- Write a method public static void division(int numerator, int denominator) that prints the result of the division of the numerator by the denominator. Keep in mind that the result of the division of the integers is an integer — in this case we want the result to be a floating point number.
Exercise 3
1 2 3 4 5 6 7 8 9 |
|