The 2 kinds
of methods in a
Java class
- A Java
class can
contain
2
kinds of
methods:
-
Instance methods:
operate on some
instance of an
object
String s1 = "abc"; // s1 references to a (String) object
s1.toUpperCase(); // Instance method acts on an object
// referenced to by s1
String s2 = "xyz"; // s2 references to another object
s1.toUpperCase(); // Instance method acts on an object
// referenced to by s2
|
-
Static/class methods:
do not
operate on any
instance of an
object
Math.pow(5,2); // Static methods do not act on objects
^^^^ // Math.pow(5,2) will always compute 52
Class name
|
|
|
More details about
instance methods
- Background information:
usage of
classes:
- Some classes are used to
store
information about
real world
things (= objects)
--- e.g.:
String that
represents text
- Other classes are
used to
organize (= group together)
utilities ---
e.g.:
Mathematical functions such as
sqrt( ), sin( ),
cos( )
|
- When a
class is
used to
store
information about
real world
things (= objects),
we can create
objects using
such class
---
e.g.:
String var1 = "abc"; // Creates an instance of a String
|
- Methods
in a
class that
operate on
an
instance of
a class are
called:
instance methods
- Syntax to
invoke an
instance method
on
the instance
var1 is:
var1.methodName( args ) // Apply "methodName" on the instance var1
|
|
More details about
static / class
methods
- Background information:
usage of
classes:
- Some classes are used to
store
information about
real world
things (= objects)
--- e.g.:
String that
represents text
- Other classes are
used to
organize
(= group together)
utilities ---
e.g.:
Mathematical functions such as
sqrt( ), sin( ),
cos( )
|
- When a
class is
used to
organize
(= group together)
utilities / methods:
- The
utilities / methods
will not
operate on
objects
|
- Methods
that
do not
operate on
instances of
classes are called:
static/class methods
- Syntax to
invoke a
static/class method is:
ClassName.methodName( args ) // Run "methodName" in the class ClassName
Example: Math.pow(2,3)
|
|
❮
❯