I\'m still learning about methods in Java and was wondering how exactly you might use an instance method. I was thinking about something like this:
public vo
If it's not a static method then it's an instance method. It's either one or the other. So yes, your method,
public void example(String random) {
// this doesn't appear to do anything
}
is an example of an instance method.
Regarding
and was wondering how exactly you might use an instance method
You would create an instance of the class, an object, and then call the instance method on the instance. i.e.,
public class Foo {
public void bar() {
System.out.println("I'm an instance method");
}
}
which could be used like:
Foo foo = new Foo(); // create an instance
foo.bar(); // call method on it
*An instance method * is a method is associated with objects, each instance method is called with a hidden argument that refers to the current object. for example on an instance method :
public void myMethod {
// to do when call code
}
Instance Variable name An object has attributes that are implemented as instance variables and carried with it throughout its lifetime. Instance variables exist before methods are called on an object, while the methods are executing and after the methods complete execution. A class normally contains one or more methods that manipulate the instance variables that belong to particular objects of the class. Instance variables are declared inside a class declaration but outside the bodies of the class’s method declarations. Each object (instance) of the class has its own copy of each of the class’s instance variables.
class InstanceMethod
{
public static void main(String [] args){
InstanceMethod obj = new InstanceMethod();// because that method we wrote is instance we will write an object to call it
System.out.println(obj.sum(3,2));
}
int f;
public double sum(int x,int y){// this method is instance method because we dont write static
f = x+y;
return f;
}
}
Instance method means the object of your class must be created to access the method. On the other hand, for static methods, as its a property of Class and not that of its object/instance, it is accessed without creating any instance of the class. But remember static methods can only access static variables, where as instance method can access the instance variables of your class. Static methods and static variables are useful for memory management as it does not require to declare objects which would otherwise occupy memory.
Example of instance method and variable :
public class Example {
int a = 10; // instance variable
private static int b = 10; // static variable (belongs to the class)
public void instanceMethod(){
a =a + 10;
}
public static void staticMethod(){
b = b + 10;
}
}
void main(){
Example exmp = new Example();
exmp.instanceMethod(); // right
exmp.staticMethod(); // wrong..error..
// from here static variable and method cant be accessed.
}