tags:

views:

71

answers:

3

hi, in Java is it valid to have the Class method with the argument as Class instance/object?

Like:

Class.method(obj)?
+2  A: 

I'm guessing you mean static method? If so, yes - it's legal:

public class MyClass {

  public static void staticMethod(MyClass parameter) {
    System.out.println("static: " + parameter.toString()); // just an example
  }

  public void instanceMethod(int parameter) {
    System.out.println("instance: " + parameter); // just an example
  }

  public static void main(String[] args) {
    MyClass instance = new MyClass();
    instance.instanceMethod(3); // invoke instance method
    MyClass.staticMethod(instance); // invoke static method
  }
ChssPly76
I think that main method would be good enought example :D It's the first lines of code that everybody starting with java get in touch
Luno
"class method" is correct. Static method is Java specific and after all static methods are indeed class methods.
OscarRyz
@Luno - OP was asking about passing object instance as an argument to a static method (at least that's the way I understood it). You can't exactly do that with `main` - hence the `staticMethod()` in my example.
ChssPly76
@Oscar - the question is java-specific, "static" is not (C# / C++ use it, for example).
ChssPly76
A: 

yes it is valid. but you should try to avoid it (except for some special cases, usually utility stuff). The class concept of java is not as nice as in other language, e.g. smalltalk or scala, where a class is an object as well. The is for example no inheritance for static methods, and it often causes problem to provide mocks for testing.

bertolami
A: 

Yes it is.

String f = "Hello %s"; // f now is an instance of string
//or
String s = new String("world"); // s is another instance of string.

Then we can use this instance as parameter of a class method, ie format method:

 String.format( f, s );

Which returns Hello world

OscarRyz