I know that variables can be categorized in two ways:-
The first way is to classify them into global and local variables based on their scope. When the variable is accessible by all the methods of an instance of a class, i.e., throughout the class, then it is known as a global variable and when it is accessible only within a block of code in an instance of a class it is known as local variable.
The the second way is to classify them into class/static instance/non-static variables. Class/static variables are those variables which belong to the class and only one copy of these variables exist for all instances of the class and it is shared by them. Instance variables are those variables which belong to the instance of the class and for which a separate copy is created for each instance.
My instructor says that instance variables can only be declared outside functions. Why is this so? Can local variables not be instance variables?
If you declare a variable inside a method, it's a local variable belonging to that method. It will go out of scope when the method is terminated. The only way to have a variable belong to an instance is to declare it directly under the class - i.e., outside of any method.
EDIT:
Here's a sample, as suggested by @Yeikel:
public class MyClass {
private static int iAmAStaticMember = 1;
private int iAmAnInstanceMember;
public void someMethod() {
int iAmALocalVariables = 4;
}
}