Java static

static

Java中static 关键字主要用于内存管理(memory management),我们可以使用static修饰变量(variables),方法(methods),代码块(block),和内部类(nested class)。 static修饰的代码属于类,而不属于类的实例(The static keyword belongs to the class than an instance of the class).

static variables

静态变量可以被当成是所有实例对象的公共属性,他在类加载的时候分配内存,而且有且仅有一次。 

static method

  • 静态方法属于类,而不属于对象实例,因此static的method里面不能使用this
  • 静态方法可以直接调用,而不用对象实例
  • 静态方法可以修改静态对象。 

java的main函数属于静态方法,这样子JVM就不需要重建对象,从而不需要额外的内存分配。

static block

  • 用于初始化静态的数据对象
  • 在类加载的时候执行静态代码块,优先于main函数的执行。

JDK1.6之前,我们可以使用静态代码块去执行程序,JDK1.7以后,一定需要main函数了。

static nested class

静态内部类不能访问非静态成员和方法,但是静态类可以直接用外部类调用。而不用实例化外部类。 

嵌套类(nested class)分为两种: 内部类(inner class)和静态嵌套类(static nested class)。 

 

内部类能够访问封闭类的成员变量,即使这些成员变量被声明为private。

静态内部类不能访问其他非静态成员变量。

嵌套类可以声明为private,protected,public,or package private,但是外部类只能声明为public or package private。 

 

嵌套类的使用场景

  1. 可以用于将两个关联紧密的类逻辑绑定在一起(It is a way of logically grouping classes that are only used in one place): If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
  2. 提高了封装。It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
  3. 提高可读性和代码可维护性: It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

内部类的使用场景,比如封装链表,Node节点只在链表重使用到,封装为private的内部类,外部看不到数据结构。 

public class LinkList<E> {

    private Node head;
    private Node tail;

    public LinkList() {
        this.head = null;
        this.tail = null;
    }

    public LinkList<E> add(E e) {
        if (head == null) {
            head = new Node(e);
            tail = head;
        }

        tail.next = new Node(e);
        tail = tail.next;

        return this;
    }

    public E pop() {
        if (head == null) {
            return null;
        }

        E value = head.elment;
        head = head.next;

        return value;
    }

    public boolean hasNext() {
        return head != null;
    }

    private class Node {
        private E elment;
        private Node next;

        public Node(E e) {
            this.elment = e;
            this.next = null;
        }
    }
    
}

静态内部类的使用场景,比如Builder,(现在虽然都用lombok.Builder 了)。

public class BankAccount {
    private long accountNumber; 
    private String owner;
    private String branch;
    private double balance;
    private double interestRate;


    //Fields omitted for brevity.
    private BankAccount() {
        //Constructor is now private.
    }


    public static class Builder {
        private long accountNumber; //This is important, so we'll pass it to the constructor.
        private String owner;
        private String branch;
        private double balance;
        private double interestRate;
        public Builder(long accountNumber) {
            this.accountNumber = accountNumber;
        }
        public Builder withOwner(String owner){
            this.owner = owner;
            return this;  //By returning the builder each time, we can create a fluent interface.
        }
        public Builder atBranch(String branch){
            this.branch = branch;
            return this;
        }
        public Builder openingBalance(double balance){
            this.balance = balance;
            return this;
        }
        public Builder atRate(double interestRate){
            this.interestRate = interestRate;
            return this;
        }
        public BankAccount build(){
            //Here we create the actual bank account object, which is always in a fully initialised state when it's returned.
            BankAccount account = new BankAccount();  //Since the builder is in the BankAccount class, we can invoke its private constructor.
            account.accountNumber = this.accountNumber;
            account.owner = this.owner;
            account.branch = this.branch;
            account.balance = this.balance;
            account.interestRate = this.interestRate;
            return account;
        }
    }
   
}

BankAccount account = new BankAccount.Builder(1234L)
            .withOwner("Marge")
            .atBranch("Springfield")
            .openingBalance(100)
            .atRate(2.5)
            .build();

 

https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

### Java 中 `static` 关键字的使用方法 #### 静态成员变量 静态成员变量属于整个类而非某个特定的对象。这意味着无论创建多少个该类的对象,这些对象共享同一个静态成员变量。 ```java public class Counter { public static int count = 0; public Counter() { count++; } } ``` 每次创建新的 `Counter` 对象时,都会使 `count` 增加一次[^1]。 #### 静态方法 静态方法也称为类方法,可以直接通过类名来调用而无需实例化任何对象。这类方法内部只能访问其他静态成员(即静态字段和其他静态方法),因为它们不依赖于具体的对象状态。 ```java public class MathUtil { public static double pi = 3.14159; // 计算圆面积的方法 public static double calculateCircleArea(double radius){ return pi * (radius * radius); } } ``` 可以这样调用上述静态方法: ```java double area = MathUtil.calculateCircleArea(5.0); System.out.println("The circle's area is " + area); ``` 这里展示了如何利用 `MathUtil` 类中的静态方法计算给定半径下的圆形面积[^2]。 #### 静态初始化块 当存在一些复杂的逻辑用于设置初始值时,可采用静态初始化块完成此类操作。它会在加载类到内存的时候执行,并且只会被执行一次。 ```java class StaticBlockExample { private static final List<String> list; static { list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); } public static String getElement(int index) { return list.get(index); } } ``` 这段代码定义了一个不可变列表并填充了一些水果名称,在后续可以通过索引来获取对应的字符串[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值