is there any way to use static-method without class?

时间:2015-11-12 11:31:48

标签: java class methods static-methods

package java;
//----------------------------- add one more line in here
class Demo {
    public static String prt(String name) {
        return "my name:" + name;
    }
}
public class Sample {
    public static void main(String[] args) {
        System.out.println(prt("hong"));
    }
}

if there is any way to print

my name : hong

,please let me know.

2 个答案:

答案 0 :(得分:2)

您可以通过使用new Demo()创建Demo类的实例来完成此操作,如下所示:

class Demo {
    public static String prt(String name) {
        return "my name:" + name;
    }
}
class Sample {
    public static void main(String[] args) {

        System.out.println(new Demo().prt("hong"));
    }
}

答案 1 :(得分:0)

You should be able to reference it via the class name:

Demo.prt("Hong")

however, if you can't use class Demo, then I'm not exactly what real life situation this would be. Methods belong to classes, they do not exist on their own. They must be referenced by classes, or instances of the class. Unless you're providing more context on your question, the answer is No.

However, if you can reference it by object, you could do this:

Demo demo = new Demo();
System.out.println(demo.prt("hong"));