English 中文(简体)
Java Beginner Question : What is wrong with the code below?
原标题:
public class Function
{
   public static void main(String args[])
   {
      System.out.println(power(3,2));
      System.out.println(power(3,2));
      System.out.println(power(2));
   }
   public long power(int m)
   {
      return m*m;
   }
   public long power(int m,int n)
   {
      long product=1;
      for(int i=1;i<=n;i++)
      {
          product=product*m;
      }
      return product;
   }
}

Compiler displays this error :-

Function.java:5: non-static method power(int,int) cannot be referenced from a static context

[edit]

Sorry about the indentation thingy :/ I ll keep that in mind from now on.

Ok so I just added static keyword and it s working fine now. What difference does this static keyword make ? I am a beginner to java and have not yet studied about what static does. I sure will read it in further chapters of the book but someone please give me an idea what it does. Thanks.

最佳回答

A shortcut rule of thumb (without full background explanation) is that static methods/functions can t call non static methods/functions so anything you want to call from your main function will need to have the static keyword in front of it.

The core issue is that Java is an object oriented language and static vs. non-static requires quite a bit of pre-requisite knowledge of object orientation. One of the disadvantages of Java is that it does require beginners to jump through a few hoops of this type as they are learning, this all stems from the object-oriented nature of Java and once you understand OO it will all fall into place (the decisions made by the language designers aren t necessarily the best ones but they are logical)

I hope you won t find it patronising if I don t go into an explanation of what static is. I can tell you that it s not a particularly difficult concept but it just relies on a few building blocks of OO concepts and a premature attempt at explanation (by me anyway) might put you off.

问题回答

As the error message says, a static method (main) cannot call a non-static method (power) without an object instance.

You should make the power methods static.

Explanation

Normal class methods are associated with an instance of the class.
For example, the String.startsWith method can only be called on a String instance. It would not make sense to call startsWith without a string instance.

Sometimes, you will want to create a method that does not require a class instance.
For example, the Integer.parseInt method is not called on an Integer instance. It wouldn t make sense to have to create an Integer instance just to be able to call Integer.parseInt.
These methods are called static methods.

main is an example of a static method. Since it is not called on an instance of your Function class, it cannot call instance methods. (Because there is no instance to call them with)

public static void main(String args[])
{
  // Create an object
  Function f = new Function( );

  System.out.println(f.power(3,2));
  System.out.println(f.power(3,2));
  System.out.println(f.power(2));
}

You are calling an instance method from a static method (main). You need to either make your power methods static, or inside main, make an instance of the Function class and call Function.power().

It s exactly what it says.

A static method doesn t need an instance of the class. You can simply do MyClass.staticMethod(). A non-static method (or instance method) operates on an instance of the class. So:

MyClass myClass = new MyClass();
myClass.instanceMethod();

You can t call the non-static method because it doesn t really exist. A non-static method only exists when it s called in the context of the instance of the class that it belongs to.

Your solution would be to make power a static method.

This is a common source of confusion for beginners. Just because a method is public and in the same class as the main method does not mean you can call it any time you like. Since main() is a static method, it has no object to call the methods on.

You can correct it in two different ways:

  1. Make both power methods static. This is the simplest way for very small programs.

    What static means is that you don t have to construct an object to call the methods. If you were calling static methods from another class it would look like Math.function(x), but since these static methods are in the same class it just looks like function(x).

  2. Create an object of the Function class and call the power methods on it. This is what you would normally do for a larger program, but here it doesn t really make sense.

    For reference, this would look like:

    Function f = new Function();
    
    System.out.println(f.power(3,2));
    System.out.println(f.power(3,2));
    System.out.println(f.power(2));
    

So, just to be clear, another way to solve this is by marking the methods as static (Remember, you can t call non-static methods from a static method, like main, but you can call static methods from a non-static method):

public class Function
{
   public static void main(String args[])
   {
      System.out.println(power(3,2));
      System.out.println(power(3,2));
      System.out.println(power(2));
   }
   public static long power(int m)
   {
      return m*m;
   }
   public static long power(int m,int n)
   {
      long product=1;
      for(int i=1;i<=n;i++)
      {
          product=product*m;
      }
      return product;
   }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签