Methods & Fields
About Method
A method in Java is a block of code that performs a specific task. Methods define the behavior of a class and are used to operate on data (fields).
Characteristics of a Method
Encapsulates Behaviour
A method contains reusable logic that can be called multiple times.
Has a Signature
In Java, a method signature consists ONLY of the method name and parameter list (type, order, and number of parameters).
Return type and access modifiers are NOT part of the method signature.
Example:
Can Take Parameters
Methods can accept input values (parameters).
Example:
Can Return a Value
A method may return a value using
return
.Example:
If no value is returned, the return type is
void
.
Access Modifiers
Determines method visibility (
public
,private
,protected
, or package-private).
Example of Methods in Java
Types of Methods in Java
1. Instance Methods
Operate on instance variables
2. Static Methods
Belong to the class, not objects
3. Abstract Methods
Declared without implementation in an abstract class
4. Final Methods
Cannot be overridden
5. Synchronized Methods
Used in multithreading
About Field
A field in Java (also called an instance variable or attribute) is a variable declared inside a class. It represents the state or properties of an object.
Local variable and Instance variable
Local variables are defined in the method and scope of the variables that exist inside the method itself.
Instance variable is defined inside the class and outside the method and the scope of the variables exists throughout the class.
Characteristics of a Field
Stores Object Data
Fields hold values that define the object's state.
Can Have Different Access Levels
Controlled by access modifiers (
private
,public
,protected
, package-private).
Can Have Default Values
Primitive types (e.g.,
int
defaults to0
,boolean
tofalse
).Reference types (e.g.,
String
defaults tonull
).
Can Be Static or Final
static
fields belong to the class, not individual objects.final
fields cannot be changed after initialization.
Example of Fields in Java
Types of Fields in Java
1. Instance Fields
Unique to each object
2. Static Fields
Shared among all objects
3. Final Fields
Cannot be reassigned
4. Transient Fields
Ignored during serialization
5. Volatile Fields
Used in multithreading to ensure consistency
Last updated
Was this helpful?