Chapter 3: Using Methods, Classes, and Objects - Notes
Understanding Method Calls and Placement
- A method is a program module containing a series of statements to carry out a task.
- To execute a method, it must be invoked or called from another method.
- The calling method (client method) makes the method call, while the called method is the one invoked.
- The
main() method executes automatically, while other methods are called as needed. - A method must include a method header (declaration) and a method body (implementation) enclosed in curly braces
{}.
Understanding Method Construction
- The method header contains optional access specifiers, a return type, an identifier, and parentheses (which may contain data to be sent to the method).
- Place the entire method within the class that will use it, not within any other method.
Access Specifiers:
- Can be
public, private, protected, or package (default). public access allows use by any other class and is the most common for methods.private access restricts use to within the same class.- The
main() method in an application must specify public access: public static void main(String[] args). - The
static modifier means that these methods do not require an object to be created.
Return Type
- Describes the type of data the method sends back to the calling method.
- If no data is returned, the return type is
void. - The
main() method must have a void return type.
Method Name
- Can be any legal identifier.
- Must be one word.
- No embedded spaces.
- Cannot be a Java keyword
- The method that executes first when you run an application must be named
main().
Parentheses
- Every method header contains a set of parentheses that follow the identifier.
- May contain data to be sent to the method
- Fully qualified identifier is a complete name that includes the class.
- The
main() method must contain String[] and an identifier (args is traditional) within its parentheses.
Adding Parameters to Methods
- Arguments are the data items you use in a call to a method.
- Parameters are the data items received by the method.
- Implementation hiding is the encapsulation of method details within a class.
- The calling method only needs to understand the interface to the called method.
- Interface is the only part of a method that the client sees or with which it interacts.
Creating a Method That Receives a Single Parameter
- Creating a method requires defining:
- Optional access specifiers
- Return type for the method
- Method name
- Parameter type
- Local name for the parameter
- Local variable:
- Known only within the boundaries of the method.
- Each time the method executes:
- The variable is redeclared
- A new memory location large enough to hold the type is set up and named
Creating a Method That Requires Multiple Parameters
- A method can require more than one parameter
- List the arguments within the call to the method and separate with commas
- Call a method: Arguments sent to the method must match the parameters listed in the method declaration by number and type.
Creating Methods That Return Values
- A return statement causes a value to be sent from the called method back to the calling method.
- The return type can be any type used in Java (primitive types, class types,
void). - Method’s type is a method’s return type.
Unreachable statements (dead code):
- Logical flow leaves the method at the return statement and can never execute causing a compiler error.
Chaining Method Calls
- Any method might call any number of other methods.
- Method acts as a black box. Do not need to know how it works; just call and use the result.
Learning About Classes and Objects
- Every object is a member of a class.
- Is-a relationships: An object “is a” concrete example of the class (e.g., the zoo’s shark “is a” Fish).
- Instantiation: Shark is an instantiation of the Fish class.
- Reusability
- Methods are often called upon to return a piece of information to the source of the request.
- Class client or class user: An application or a class that instantiates objects of another prewritten class
Creating a Class
- Assign a name to the class.
- Determine what data and methods will be part of the class.
- Create a class header with three parts:
- An optional access modifier
- The keyword
class - Any legal identifier for the name of the class
public class: Accessible by all objects- Extended: To be used as a basis for any other class
- Data fields: Variables declared within a class but outside of any method.
- Instance variables: Nonstatic fields given to each object.
- Private access for fields: No other classes can access the field’s values; Only methods of the same class are allowed to use private variables
- Most class methods are public
Creating Instance Methods in a Class
- Classes contain methods:
- Mutator methods: Set or change field values.
- Accessor methods: Retrieve values.
- Nonstatic methods:
- Instance methods
- “Belong” to objects
- Typically declare nonstatic data fields
- Static class variables are not instance variables.
Static vs Nonstatic
- Static:
- Keyword:
static - Static fields: Class fields
- Static methods: Class methods
- Usage: Do not use an object (e.g.,
JOptionPane.showDialog();) - Memory: One copy of the field exists in memory (if 100 objects are instantiated).
- Method this reference: The method does not receive
this reference. - Static class variables are not instance variables.
- Nonstatic:
- Keyword: No specific keyword (default).
- Nonstatic fields: Instance variables.
- Nonstatic methods: Instance methods.
- Usage: Must use an object (e.g.,
System.out.println();) - Memory: 100 copies of the field exist in memory (if 100 objects are instantiated).
- Method this reference: The method receives a
this reference. - Instance fields and methods are nonstatic.
Organizing Classes
- Place data fields in logical order at the beginning of a class and list the fields vertically
- Data fields and methods may be placed in any order within a class
- It’s common to list all data fields first; Names and data types can be seen before reading the methods that use the data fields
Declaring Objects and Using Their Methods
- Declaring a class does not create any actual objects
- To create an instance of a class:
- Supply a type and an identifier
- Allocate computer memory for the object
- Use the
new operator (e.g., Employee someEmployee = new Employee();)
- Reference to the object is the name for a memory address where the object is held
- Constructor method: A method that creates and initializes class objects
- You can write your own constructor methods
- Java writes a constructor when you don’t write one
- The name of the constructor is always the same as the name of the class whose objects it constructs
- After an object is instantiated, its methods can be accessed using the object’s identifier, a dot, and a method call
Understanding Data Hiding
- Data hiding using encapsulation: Data fields are usually private, and the client application accesses them only through public interfaces
- Set method: Controls the data values used to set a variable
- Get method: Controls how a value is retrieved
An Introduction to Using Constructors
Employee chauffeur = new Employee(); is actually a calling method named Employee()- Default constructors require no arguments and are created automatically by a Java compiler for any class whenever you do not write a constructor
- Numeric fields are set to 0 (zero).
- Character fields are set to Unicode ‘\u0000’.
- Boolean fields are set to false.
- Nonprimitive object fields are set to null.
- A constructor method:
- Must have the same name as the class it constructs
- Cannot have a return type
- Public access modifier
Understanding That Classes Are Data Types
- Classes you create become data types, often referred to as abstract data types (ADTs).
- Implementation is hidden and accessed through public methods.
- Programmer-defined data type, not built into the language.
- Declare an object from one of your classes by providing the type and identifier.
Common Mistakes
- Placing a semicolon at the end of a method header
- Thinking “default constructor” means only the automatically supplied constructor
- Thinking that a class’s methods must:
- Accept its own fields’ values as parameters
- Return values to its own fields
- Creating a class method that has a parameter with the same identifier as a class field