Reputation: 8005
When studying the java programming language, I meet the following statement
I am confusing about the statement marked with yellow. Especially, what does instance method mean here? If there is an example to explain this point, then it would be much appreciated.
Upvotes: 0
Views: 101
Reputation: 1
First of all, you should understand the difference between the class method and the instance method. An example is shown below.
public Class Example{
public static void main(String[] args) {
Example.method1();//or you can use method1() directly here
Example A = new Example();
A.method2();
}
public static void method1(){
}
public void method2(){
}
}
method1
is the class method which you can take it as the method of the class. You can invoke it without initiating a object by new method. So you can invoke it in such way: Example.method1()
method2
is the instance method which requires you to invoke it by initiating the instance of an object, i.e. Example A = new Example(); A.method2();
Additional:
The error is due to the removal of the static
modifier of an class method like method1
. Then method1
becomes an instance method like method2
which you have to initiate an instance to call.
Upvotes: 0
Reputation: 28752
Consider following sequence.
Class X
with static void foo()
a static methodClass Y
which calls X.foo()
in its main method
X.foo()
to be a instance
method by removing the static
qualifierX
, not Y
Y
class again and observe the error.On the other hand, if you had changed the body of X.foo
in certain ways without changing its static-ness
then there would have been no error. For more, look up "binary compatibility"
Upvotes: 1
Reputation: 3510
You can call static methods without needing to intantiate an object:
TestObject.staticMethodCall();
For non-static methods you need to create an instance to call a method on:
new TestObject().nonStaticMethodCall();
Upvotes: 1
Reputation: 11572
If I have a method:
public static void print(String line) {
System.out.println(line);
}
... and then remove the static
keyword ...
public void print(String line) {
System.out.println(line);
}
... it is now an instance method, can no longer be invoked from the class, and must instead be invoked from an instance (hence the name).
e.g.,
MyClass.print(line);
vs.
new MyClass().print(line);
That's really it.
Upvotes: 6