编写static代码块:优化程序性能上起着关键作用

static方法(是方法 方法 方法 不是类)是没有this的方法。在static方法中内部不能调用非静态方法,而且可以在没有创建任何对象的前提下,仅仅通过类本身来调用static方法。方便在没有创建对象的情况下来进行调用(方法/变量)。

1.static方法:

静态方法中不能访问类的非静态成员变量和非静态成员方法。

非静态成员方法中是可以访问静态成员方法/变量的。

java中static关键字的深度学习

2.static变量:

3.static代码块:可以优化性能

比如常规的代码:

class Person{
    private Date birthDate;
     
    public Person(Date birthDate) {
        this.birthDate = birthDate;
    }
     
    boolean isBornBoomer() {
        Date startDate = Date.valueOf("1946");
        Date endDate = Date.valueOf("1964");
        return birthDate.compareTo(startDate)>=0 && birthDate.compareTo(endDate) < 0;
    }
}

使用static代码怪改良的代码:

class Person{
    private Date birthDate;
    private static Date startDate,endDate;
    static{
        startDate = Date.valueOf("1946");
        endDate = Date.valueOf("1964");
    }
     
    public Person(Date birthDate) {
        this.birthDate = birthDate;
    }
     
    boolean isBornBoomer() {
        return birthDate.compareTo(startDate)>=0 && birthDate.compareTo(endDate) < 0;
    }
}

 

面试题:

public class Test {
    Person person = new Person("Test");
    static{
        System.out.println("test static");
    }
     
    public Test() {
        System.out.println("test constructor");
    }
     
    public static void main(String[] args) {
        new MyClass();
    }
}
 
class Person{
    static{
        System.out.println("person static");
    }
    public Person(String str) {
        System.out.println("person "+str);
    }
}
 
 
class MyClass extends Test {
    Person person = new Person("MyClass");
    static{
        System.out.println("myclass static");
    }
     
    public MyClass() {
        System.out.println("myclass constructor");
    }
}

结果:

test static
myclass static
person static
person Test
test constructor
person MyClass
myclass constructor

 

参考博客:https://www.cnblogs.com/dolphin0520/p/3799052.html

 

 

 

 

相关文章:

  • 2022-12-23
  • 2021-07-09
  • 2021-12-13
  • 2021-07-24
  • 2021-09-23
  • 2021-10-28
猜你喜欢
  • 2021-05-18
  • 2021-10-03
  • 2021-09-25
  • 2021-12-11
  • 2021-11-04
  • 2021-09-26
  • 2022-02-20
相关资源
相似解决方案