1、类为默认的修饰符
class Helloworld {
static public void main(String[] nima) {
System.out.println("hello world!");
}
}
无编译错误
hello world!
2、类为public修饰符
public class Helloworld {
public static void main(String[] nima) {
System.out.println("hello world!");
}
}
无编译错误
运行结果:
hello world!
3、类且方法的修饰符为默认
class Helloworld {
static void main(String[] args) {
System.out.println("hello world!");
}
}
无编译错误
运行结果:错误: 在类 date1109.helloworld.Helloworld 中找不到主方法, 请将主方法定义为:
public static void main(String[] args)
4、类的修饰符为public且方法的修饰符为默认
public class Helloworld {
static void main(String[] args) {
System.out.println("hello world!");
}
}
无编译错误
运行结果:
错误: 在类 date1109.helloworld.Helloworld 中找不到主方法, 请将主方法定义为:
public static void main(String[] args)
5、类的修饰符为public且方法的修饰符为protected
public class Helloworld {
protected static void main(String[] args) {
System.out.println("hello world!");
}
}
无编译错误
运行结果:错误: 在类 date1109.helloworld.Helloworld 中找不到主方法, 请将主方法定义为:
public static void main(String[] args)
6、类的修饰符为public且方法的修饰符为private
public class Helloworld {
private static void main(String[] args) {
System.out.println("hello world!");
}
}
无编译错误
运行结果:错误: 在类 date1109.helloworld.Helloworld 中找不到主方法, 请将主方法定义为:
public static void main(String[] args)
……
去掉static修饰符,同样没有编译错误,但无法正确运行。
7、类的修饰符为public,方法修饰符为public,但没有static
public class Helloworld {
public void main(String[] args) {
System.out.println("hello world!");
}
}
无编译错误
运行结果:
错误: main 方法不是类 date1109.helloworld.Helloworld 中的static, 请将 main 方法定义为:
public static void main(String[] args)
8、类的修饰符为public,方法的修饰符为protected,但没有static
public class Helloworld {
protected void main(String[] args) {
System.out.println("hello world!");
}
}
无编译错误
运行结果:
错误: 在类 date1109.helloworld.Helloworld 中找不到主方法, 请将主方法定义为:public static void main(String[] args)
9、类的修饰符为public,方法的修饰符为private,但没有static
public class Helloworld {
private void main(String[] args) {
System.out.println("hello world!");
}
}
无编译错误
运行结果:
错误: 在类 date1109.helloworld.Helloworld 中找不到主方法, 请将主方法定义为:public static void main(String[] args)
10、类的修饰符为public,方法的修饰符为默认,但没有static
public class Helloworld {
void main(String[] args) {
System.out.println("hello world!");
}
}
无编译错误
运行结果:
错误: 在类 date1109.helloworld.Helloworld 中找不到主方法, 请将主方法定义为:public static void main(String[] args)
总结:
1、程序中主方法的修饰符必须为public 与 static 同时修饰。主方法的形如:public static void main( String args[] ){ }、static public void main( String args[]){ }、public static void main( String[] nima ){ } 等,其中,主方法参数args的类型为String数组,参数名没有硬性要求,也即参数名不是args也可以正确运行。
2、public ,final 与 static 都是修饰符,排名不分先后。例如一个常量可以这样写:
final static public int s = 6;
也可以这样写:
public final static int s = 6;
3、最外层的类不能使用static修饰,编译报错。内部类可以。
4、访问权限修饰符的访问权限排名:
public > protected > default > private
说明:
private :仅本类成员可见
default :本类+同包类可见(默认)
protected:本类+同包+不同包的子类
public :公开
注:这里的同包指的是跟父类所在的包相同。