static关键字

静态与非静态间的调用

package cn.dailylearn.api;
/*
 * 如果一个对象使用了static关键字,那么这个变量不再属于对象自己,而是属于所在的类,多个对象共享同一个数据
 * 一旦使用static修饰成员方法,那么这就成为了静态方法,静态方法不属于对象,而是属于类
 * 静态不能直接访问非静态
 * */
public class dl_static {
    int num;//成员变量
    static int static_num;//静态变量

    public static void main(String[] args) {
        Person studentPerson = new Person("A", 18);
        Person stPerson = new Person("B", 19);
        studentPerson.roomString = "XXX";
        
        System.out.println(stPerson.roomString);
        System.out.println(studentPerson.getId());
        System.out.println(stPerson.getId());
        
        Person.static_method();
        studentPerson.method();
        
//      对于本类的静态方法,可以省去前面的类名称
        name();

    }
    //静态方法 
    public static void name() {
        System.out.println("自己的静态方法");
//      静态方法中不能使用this关键字
//      System.out.println(num); 报错,静态不能直接访问非静态 --- 先有静态,后有非静态
        System.out.println(static_num);
    }
    //成员方法   --成员方法可以访问成员变量和静态变量
    public void method() {
        System.out.println(num);
        System.out.println(static_num);
    }
}

static内存使用情况

static内存使用情况

static代码块

package ContructorTest;

import java.util.Random;

public class ContructorTest {
    public static void main(String[] args) {
        Employee[] staff = new Employee[3];
        
        System.out.println("#####################");
        staff[0] = new Employee("Harry", 18000);
        System.out.println("#####################");
        staff[1] = new Employee(15000);
        System.out.println("#####################");
        staff[2] = new Employee();
        
        for (Employee employee : staff) {
            System.out.println("name = " + employee.getName() + "id = " + employee.getId() + "salary = " + employee.getSalary());
        }
    }
}

class Employee
{
    private static int nextId;
    
    private int id;
    private String name = "";
    private double salary;
//第一次初始化的时候运行且只运行一次
    static 
    {
        System.out.print("static代码块,只运行一次\n");
        Random generator = new Random();
        nextId = generator.nextInt(10000);
    }
//  每次初始化时都运行
    {
        System.out.println("每次初始化都运行");
        id = nextId;
        nextId ++ ;
    }
    
    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }
    
    public Employee(double salary) {
        this("Employee #" + nextId, salary);
    }
    
    public Employee() {
        
    }
    
    public String getName() {
        return name;
    }
    
    public double getSalary() {
        return salary;
    }
    
    public int getId(){
        return id;
    }
}

你可能感兴趣的:(static关键字)