Can we print a java message on console without using main method, static variable and static method?

半腔热情 提交于 2019-12-05 08:24:36
Mena

Of course you can, from a class constructor, method or instance block for instance.

However if you're talking about launching a simple program with the command line (e.g. java -jar myProgram), you'll still need to instantiate the class where the instance code printing to console resides, in a main method.

For instance, with given class Foo:

public class Foo {
    // Initializer block Starts
    { 
        System.out.println("Foo instance statement");
    }
    // Initializer block Ends

    public Foo() {
        System.out.println("Foo ctor");
    }
    public void doSomething() {
        System.out.println("something done from this Foo");
    }
}

... now from the main method of your Main class:

public static void main(String[] args) {
    new Foo().doSomething();
}

Output:

Foo instance statement
Foo ctor
something done from this Foo
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!