Java中什么叫主函数

Python022

Java中什么叫主函数,第1张

比如下面的Java程序:

public class Demo {

    public static void main(String[] args) {

        System.out.println("Hello World!")

    }

}

这里面的:

public static void main(String[] args) {

    System.out.println("Hello World!")

}

就是主函数

看看我的代码对你有帮助:

这是第一个问题:

package

com.andy

public

class

hello

{

/**

*

@param

args

*/

public

static

void

main(String[]

args)

{

//

TODO

Auto-generated

method

stub

int

a=100//a是可以被打印出来的,不加static。

System.out.print("这是来自

hello的

方法")

System.out.print(a)

}

}

这是第二个问题:

package

com.andy

public

class

NewMain

{

public

static

void

main(String[]

args)

{

//

TODO

Auto-generated

method

stub

int

a=100//a是可以被打印出来的。

System.out.print("这是来自

NewMain的

主方法,它还调用了来自Hello的主方法")

String[]

str={"AAA","BBB","CCC"}

com.andy.hello.main(str)

System.out.print(a)

}

}

在你的IDE里面建立一个包:com.andy

然后建立两个类:hello,NewMain,运行一下,你就明白了,希望对你有帮助,Good

Luck。

你说的对, 静态的方法确实只能调用其他的静态方法或成员变量.main函数也是静态函数, 这也没错. 不过main函数中调用的其他函数确实都是静态方法. 而非静态的方法则需要实例化之后再能使用实例化之后的对象进行调用, 举个例子:package org.hotleave.testpublic class Test {

/**

* 非静态方法

*/

public void normalFunction() {

System.out.println("this is a normal function, should be call by a instance")

}

/**

* 静态方法

*/

public static void staticFunction() {

System.out.println("this is a static function, can be called by the class")

}

/**

* @param args

*/

public static void main(String[] args) {

// 调用 自身的静态方法

staticFunction()

// 通过类名调用自身的静态方法

Test.staticFunction()

// 调用其他类的静态方法

A.staticFunction()

// 调用自身的非静态方法

Test test = new Test()

test.normalFunction()

// Test.normalFunction()// 报错: 静态方法不能访问非静态方法或成员变量

// 调用其他类的非静态方法

A a = new A()

a.normalFunction()

// A.normalFunction()// 报错: 静态方法不能访问非静态方法或成员变量

}}

class A {

public void normalFunction() {

System.out.println("this is a normal function, should be call by a instance")

}

public static void staticFunction() {

System.out.println("this is a static function, can be called by the class")

}

}