Apuntes
Sin título
Contenido del apunte (3)
Página 1
DESIGNING METHODS
Parts of a Method Declaration
• A method declaration specifies all the information needed to
call a method.
• Example of a method declaration:
public final void nap(int minutes) throws Exception {
//statements
}
• The parts of a method declaration are as follows:
Element Value in nap()
example
Required?
Access modifier public No
Optional specifier final No
Return type void Yes
Method name nap Yes
Parameter list (int minutes) Yes, but can be
empty ( )
Optional
exception list
throws Exception No
Method body {
//statements
}
Yes, but can be
empty { }
To call the nap() method, just type its name followed by a
single int value in parentheses. Ex. nap(15);
• An access modifier specifies whether other classes can use
a particular field or invoke a particular method. The access
modifiers in Java are public, protected, package-private
(no modifier), and private.
• The most common optional specifiers are the following:
o static is used for class methods.
o abstract is used when a method does not have a
body.
o final is used when a method is not allowed to be
overridden by a subclass.
• Return type is the data type of the value returned by the
method, or void if the method does not return a value.
IT1908
• The method name should follow the naming convention rules
below:
o Should be a verb in lowercase (ex. run); or
o A multi-word name that begins with a verb in lowercase,
followed by adjectives, nouns, etc., that starts with
capital letters (ex. runFast)
• The parameter list is a comma-delimited list of input
parameters, preceded by their data types and enclosed by
parentheses. Empty parentheses are allowed if there are no
parameters specified.
• The optional exception list indicates that the method might
throw one of the listed exception types.
• The method body is everything that is enclosed between
braces. It contains the method’s code including the
declaration of local variables.
Access Modifiers
• Two (2) levels of access control:
o Top level – public or package-private
o Member level – public, private, protected, or
package-private
• The public modifier allows the method to be visible to all
classes everywhere.
• The private modifier specifies that the method can only be
accessed in its own class.
• The protected modifier specifies that the member can only
be accessed within its own package and by a subclass of its
class in another package.
• The package-private modifier (no modifier) specifies that
the member can only be accessed within its own package.
Página 2
STATIC METHODS AND FIELDS
Fundamentals
• A static variable or class variable is any field declared with
the static modifier; this tells the compiler that there is exactly
one (1) copy of this variable in existence, regardless of how
many times the class has been instantiated.
Example:
public class StaticVarDemo {
static int count = 0;
public void increment() {
count++;
}
public static void main(String args[]) {
StaticVarDemo obj1 = new StaticVarDemo();
StaticVarDemo obj2 = new StaticVarDemo();
obj1.increment();
System.out.println("Obj1: count = "+ obj1.count);
obj2.increment();
System.out.println("Obj1: count = "+ obj1.count);
System.out.println("Obj2: count = "+ obj2.count);
}
}
Output: count is a static variable, while increment is a
method whose task is to increase the value of the count
variable by 1. In the main method, two (2) objects are created,
named obj1 and obj2. obj1 invoked the increment method
and showed the value of 1. Then, obj2 also invoked the
increment method, resulting in obj1 having also the value of
2. This is because count is a static variable. Only a single
copy of a static variable is created and shared among all the
instances of the class.
Explanation:
• A static method belongs to the class rather than the object
of a class.
o It can be invoked without creating an instance of a
class.
o It can access static members and change their
values.
• Static methods have two (2) main purposes:
o For utility or helper methods that don’t require any
object state: Since there is no need to access
instance variables, having static methods eliminates
the need for the caller to instantiate the object just to
call the method.
o For a state shared by all instances of a class (like a
counter): All instances must share the same state.
Methods that merely use that state should be static
as well.
• To call a static method or variable, put the class name before
the method or variable.
Example:
class NumberClass {
public static int num = 0;
public static void displayNumber() {
System.out.print(num);
}
}
public class NumberClassDemo {
public static void main(String[] args) {
System.out.print(NumberClass.num);
NumberClass.displayNumber();
}
}
Output: 00
• An instance of an object can be used to call a static method
or update a static variable.
Example:
public class NumberClass {
public static int num = 0;
public static void main(String[] args) {
NumberClass.num = 4;
NumberClass nc1 = new NumberClass();
NumberClass nc2 = new NumberClass();
nc1.num = 6;
nc2.num = 5;
System.out.print(NumberClass.num);
}
}
Output: 5
Explanation: There is only one (1) num variable since it is
static.Static versus Instanc
e
• An instance variable or method is any variable or method
that is non
-static.
o It requires an object of its class to be created before
it can be used or called.
• An instance variable is any variable that is declared outside
any method, constructor, or block.
Type Acces
sing Legal? How?
Static
method
Another static
method or variable
Yes Using the class name
Static
method
An instance method
or variable
No
Instance
method
A static method or
variable
Yes Using the class name
or reference variable
Instance
method
Another instance
method or variable
Yes Using a reference
variable
Example of a static method calling an instance method:
public class NumberClass {
public static int num = 0;
public static void main(String[] args) {
displayNumber(); //does not compile
}
public void displayNumber() {
System.out.print(num
)
;
}
}
Example of a static method trying to access an instance variable:
public class NumberClass {
int num = 0;
public static void main(String[] args) {
displayNumber();
}
public static void displayNumber() {
System.out.print(num
)
; //does not compile
Página 3
METHOD OVERLOADING
Passing Information to a Method
• Parameters are the variables listed in a method declaration.
Ex. public double computeSalePrice(double
origPrice, double discountRate) { }
• Arguments are the actual values that are passed in when the
method is invoked.
Ex. computeSalePrice(37.50, 0.15)
• Java is a pass-by-value language. This means that a copy of
the variable is made, and the method receives that copy.
Ex. main() method calls newNumber() method
public static void main(String[] args) {
int num = 1;
newNumber(2);
System.out.println(num);
}
public static void newNumber(int num) {
num = 3;
}
Output: 1
Explanation: The variable num in main() does not change
even after calling it because no assignments are made to it.
Overloading Methods
• A method signature consists of the method’s name and the
parameter types.
Ex. The method signature of computeSalePrice(double
origPrice, double discountRate) is
computeSalePrice(double, double)
• Method overloading occurs when there are different method
signatures with the same name but different type parameters.
Ex.
public void draw(String s) { }
public void draw(int i) { }
public void draw(int i, double f) { }
Thus, you can create statements like the following:
draw(“Circle”);
draw(10);
draw(10, 5.0);
• Overloaded methods are differentiated by the number and the
type of arguments passed into the method.
• You cannot declare more than one (1) method with the same
name and the same number and type of arguments.
• You cannot declare two (2) methods with the same signature
even if they have different return types.
Ex.
public void draw(int i) { }
public int draw(int i) { } //does not compile
Autoboxing
• Autoboxing is the automatic conversion that the Java
compiler makes between the primitive types and their
corresponding object wrapper classes.
Ex. int to Integer, double to Double
• When the primitive type version is not present, Java performs
autoboxing.
public void draw(Integer i) {
System.out.print(“Integer”);
}
Calling statement: draw(10);
Output: Integer
• When the primitive type version is present, Java does not
need to perform autoboxing.
Ex.
public void draw(Integer i) {
System.out.print(“Integer”);
}
public void draw(int i) {
System.out.print(“int”);
}
Calling statement: draw(10);
Output: int
Información
- Descripción
- Apunte sobre Sin título, creado por kenth monday el 27/08/2025.
- Creado por
- kenth monday
- Visitas
- 0
- Valoración