user297850
user297850

Reputation: 8005

regarding static method in java

When studying the java programming language, I meet the following statement

enter image description here

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

Answers (4)

cc13ny
cc13ny

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

Miserable Variable
Miserable Variable

Reputation: 28752

Consider following sequence.

  1. Define Class X with static void foo() a static method
  2. Define Class Y which calls X.foo() in its main method
  3. Compile the two classes and (somehow) run it
  4. Change X.foo() to be a instance method by removing the static qualifier
  5. Compile only X, not Y
  6. Run the 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

Zhedar
Zhedar

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

asteri
asteri

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

Related Questions