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;
   }
}

The compiler displays this error: -

.Java function: 5: non-static ability of a method (int, int) cannot be specified from a static context

[edit]

Sorry for the indentation: / I will keep this in mind from now on.

So, I just added a static keyword, and now it works great. What difference does this static keyword make? I am new to java and have not yet studied what static is. I will definitely read it in subsequent chapters of the book, but someone, please give me an idea of ​​what he is doing. Thank.

+3
source share
7 answers

( ) , / /, , , .

, Java - - , . Java , , - Java, OO, ( , , , )

, , , . , , ( ) .

+4

, (main) (power) .

power.

.
, String.startsWith String. startsWith .

, .
, Integer.parseInt Integer. Integer, Integer.parseInt.
static.

main static. Function, . ( )

+9
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));
}
+3

static (main). power , main, Function Function.power().

+2

, .

. MyClass.staticMethod(). ( ) . :

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

, . , , .

power.

+2

. , , main, , . main() , .

:

  • power static. .

    static, , . , Math.function(x), , function(x).

  • Function power . , , .

    :

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

So, in order to be clear, another way to solve this is to mark methods as static (remember, you cannot call non-static methods from a static method, for example 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;
   }
}
+1
source

Source: https://habr.com/ru/post/1750152/


All Articles