1.修饰成员变量(类变量)
public class Student{
String name; //实例变量,由每个对象所有
static int age;//类变量,由类所有
}
public class Test{
public static void main(String[] args){
Student.age=10;
//通过类名调用age
Student s1=new Student();
System.out.println(s1.age);
//通过对象名调用age
Student s2=new Student();
System.out.println(s2.age);
}
}

s1,s2有相同的age
好处:只占一份内存,且可以被共享
public class User{
public static int number;
public User(){
User.number++;
}
}
public class test{
public static void main(String[] args){
User u1=new User();
System.out.println(User.number);
}
}

2.修饰成员方法(类方法)
public class Student{
String name;
//类方法
public static void hello(){
System.out.println("hello");
}
//实例方法
public void printname(){
System.out.println(this.name);
}
}
public class test{
public static void main(String[] args){
Student.hello();//通过类名调用类方法
Student s1= new Student();
s1.name="John";
Student s2= new Student();
s2.name="kim";
s1.hello();//通过对象调用类方法
s1.printname();//调用实例方法
s2.printname();
}
}


类方法的好处:提高代码复用性


代码块
public class Student {
String name;
static int age;
//静态代码块
//初次加载类时执行,只执行一次
static{
System.out.println("静态代码块执行了~");
age = 18;
}
//实例代码块
//构造对象时先执行,再构造对象
{
System.out.println("实例代码块执行了~");
System.out.println(this.age);
}
Student(){
System.out.println("无参数构造器执行了");
}
Student(String name){
System.out.println("有参数构造器执行了");
this.name = name;
System.out.println(this.name);
}
}
public class Test{
public static void main(String[] args){
Student s1= new Student();
Student s2= new Student("kim");
}
}
}


main方法

注意事项
