Class method with class instace/object as arguments
in Java is it valid to have the Class method开发者_如何学JAVA with the argument as Class instance/object?
Like:
Class.method(obj)?
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
}
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.
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
精彩评论