public static void main(String[] args) {...}
public:公共的,访问权限是最大的。
由于main方法是被jvm调用,所以权限要够大。
static:静态的,不需要创建对象,通过类名就可以。方便jvm的调用。
void:方法的返回值是返回给调用者,而main方法是被jvm调用。你返回内容给jvm没有意义。
main:是一个常见的方法入口。我见过的语言都是以main作为入口。
String[] args:这是一个字符串数组。
早期是为了接收键盘录入的数据的。
格式是:java MainDemo hello world java
- 代码解释
class MainDemo {
public static void main(String[] args) {
//System.out.println(args); //[Ljava.lang.String;@175078b
//System.out.println(args.length); //0
//System.out.println(args[0]); //ArrayIndexOutOfBoundsException
//接收数据后。 java MainDemo hello word java 传入数据。
System.out.println(args);
System.out.println(args.length);
//System.out.println(args[0]);
for(int x=0; x<args.length; x++) {
System.out.println(args[x]);
}
}
}
定义一个人类,接受每个人的姓名、年龄、国籍;姓名和年龄是变化的,国际是不变的,所以每次创建对象的时候在堆内存开辟同样的空间很浪费,针对这种多个对象有同样的成员变量值的时候,java提供了一个static关键字来修饰
静态修饰的内容一般我们称其为:与类相关的,类成员
如果某个成员变量是被所有对象共享的,那么它就应该定义为静态的。
- static的特点:
修饰成员变量,还可以修饰成员方法
1. 随着类的加载而加载。 //回想main方法
2. 优先于对象存在。
3. 被类的所有对象共享。 //班级的学生共用同一个班级编号
4. 可以通过类名调用。 //也可以通过对象名调用。推荐通过类名调用。
- static关键字注意事项
1. 静态方法中没有this关键字
静态是随着类的加载而加载,this是随着对象的创建而存在,所以static(静态)比this(对象)先存在。
2. 静态方法只能访问静态的成员变量和静态的成员方法。【静态只能访问静态。】
//非静态方法可以访问静态或非静态的的成员变量和成员方法。
- 代码详解
- 静态变量的调用
class Student {
int num = 10; //非静态变量
static int num2 = 20; //静态变量
}
class StudentDemo {
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.num); //非静态变量的调用
System.out.println(Student.num2); //静态变量的调用。 [推荐]这种使用类名进行静态变量的调用。
System.out.println(s.num2); //静态变量的调用。
}
}
class Person {
String name;
int age;
//String country;
static String country; //静态成员变量
//三个构造方法
public Person(){}
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public Person(String name,int age,String country) {
this.name = name;
this.age = age;
this.country = country;
}
public void show() {
System.out.println("姓名:"+name+",年龄:"+age+",国籍:"+country);
}
}
class PersonDemo {
public static void main(String[] args) {
//创建对象1
Person p1 = new Person("邓丽君",16,"中国");
p1.show();
//创建对象2
//Person p2 = new Person("杨幂",22,"中国");
//p2.show();
Person p2 = new Person("杨幂",22);
p2.show();
//创建对象3
//Person p3 = new Person("凤姐",20,"中国");
//p3.show();
Person p3 = new Person("凤姐",20);
p3.show();
p3.country = "美国";
p3.show();
p1.show();
p2.show();
}
}
class Teacher {
public int num = 10;
public static int num2 = 20;
public void show() {
System.out.println(num); //隐含的告诉你访问的是成员变量
System.out.println(this.num); //明确的告诉你访问的是成员变量
System.out.println(num2);
//function();
//function2();
}
public static void method() {
//无法从静态上下文中引用非静态 变量 num
//System.out.println(num);
System.out.println(num2);
//无法从静态上下文中引用非静态 方法 function()
//function();
function2();
}
public void function() {
}
public static void function2() {
}
}
class TeacherDemo {
public static void main(String[] args) {
//创建对象
Teacher t = new Teacher();
t.show();
System.out.println("------------");
t.method();
}
}