Without methods, an object cannot do anything.
Method Invocation
Without methods, an object cannot do anything. When an object calls a method, it
is actually requesting to perform some action like to set a value, return a
value, write to a file or to provide some functionality required.
There are two types
of method invocation in java:
i) Class method
ii) Instance method
i.) Class method : Method invocation on
a class
A method that is invoked on a class instead of
on an actual object. Methods are class methods if they contain the static
keyword in their declaration.
static
modifier in their declarations. They
should be invoked with the class name, and they do not need an instance of a
class to be created, as in
ClassName.methodName(args)
Note: An object reference can also be used to refer to the static methods like
instanceName.methodName(args)
Commonly it is used for static methods to access static fields e.g. adding a static method to the Car class to access its color static field:
public static int getColor () {
return color ;
}
Class
methods don't need any instance for invoking and it uses the static binding. In
the class method it select the reference of the object at compile time.
ii.) Instance method: Method invocation on a class instance
In object-oriented programming language objects play a crucial
role. Objects need methods
to do something. And to invoke these instance method it need an
instance of a class to be created. The actual logic behind the method invoking
begins when an
object calls a method requesting to perform some
action.
Data that are passed to a method are known as arguments, the
required arguments for a method are defined by a method's constraint list.
Note : Not all combinations of instance and class variables and methods are allowed:
- Instance methods can access instance variables and instance methods directly.
- Instance methods can access class variables and class methods directly.
- Class methods can access class variables and class methods directly.
- Class methods cannot access instance variables or instance methods directly?they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.