-2

I have a class with static method which will be invoked from same class method and from other class using Class.staticmethod. something like this,

ClassA{
 public void method1(){
     ---
     ---
     method2();
 }
 public static void method2(){
    ---
    ---
 }
}

ClassB{
  public void call(){
    ClassA.method2(); //i have to invoke through static method.
  }
}

public void main(...){
 ClassA obj = new ClassA();
 obj.method1();
}

Is the code follow the standard (Section 10.2 of Java conventions)? or i should invoke ClassA.method2() in classA method1. Please dont say this is a duplicate, I have looked at the other questions, they don't talk about this scenario.

Community
  • 1
  • 1
skumar
  • 985
  • 4
  • 14
  • 37
  • 3
    [Funnily enough, the conventions you mention *explicitly* mention that the usage you describe is OK.](http://javascript.crockford.com/javacodeconventions.pdf) – Makoto Apr 27 '15 at 21:43
  • `ClassA::method1` is useless if its job is to call `ClassA.method2()`. You should remove it and always use `ClassA.method2()`. – Happy Apr 27 '15 at 21:43
  • 1
    @Happy that's just code example to show OP's intentions. – Luiggi Mendoza Apr 27 '15 at 21:44
  • 1
    @Makoto I agree - it is funny, since it actually really bad coding style ;-) – RudolphEst Apr 27 '15 at 21:44
  • I'm not clear on what you are asking. Is it "how should I call a static method? from an instance or just by itself? If so, the answer is it depends on your situation, but in the situation you presented you should call it directly. – David says Reinstate Monica Apr 27 '15 at 21:44
  • 1
    Your example code is consistent with the Java coding conventions document. However, although those conventions are widely adopted, it's incorrect to call them a "standard". – John Bollinger Apr 27 '15 at 21:47
  • 1
    @LuiggiMendoza Yeah you probably right but never forget that some beginners can find this question, so it's valuable mentioning that. – Happy Apr 27 '15 at 21:47
  • @Happy, method1 has some lines for code and then it invokes method2. i have just updated the question. – skumar Apr 27 '15 at 21:49

1 Answers1

2

As the conventions state (thanks to Makoto), you should refrain from using an object reference to call a static method. That means, do not do this:

someObject.staticMethod();

Instead, use the Class name like this:

SomeClass.staticMethod();

Of course, if you are calling the static method from within that class it is ok (and probably preferred) to do this:

staticMethod();
Community
  • 1
  • 1
StrongJoshua
  • 975
  • 10
  • 24