静态static关键字

在类中,用static声明的成员变量为静态成员变量,也称为类变量。类变量的生命周期和类相同,在整个应用程序执行期间都有效。

注:static修饰的成员变量和方法,从属于类

  普通变量和方法从属于对象

  静态方法不能调用非静态成员,编译会报错

static关键字的用途:方便在没有创建对象的情况下进行调用方法或变量,被static关键字修饰的方法或者变量不需要依赖于对象来进行访问,只要类被加载了,就可以通过 类名.方法名或变量名进行访问。

static可以用来修饰类的成员方法、类的成员变量,另外也可以编写static代码块来优化程序性能

 

static方法
static方法也成为静态方法,由于静态方法不依赖于任何对象就可以直接访问,因此对于静态方法来说,是没有this的,因为不依附于任何对象,并且由于此特性,在静态方法中不能访问类的非静态成员变量和非静态方法,因为非静态成员变量和非静态方法都必须依赖于具体的对象才能被调用。

 

static变量
static变量也称为静态变量,静态变量和非静态变量的区别:

静态变量被所有对象共享,在内存中只有一个副本,在类初次加载的时候才会初始化

非静态变量是对象所拥有的,在创建对象的时候被初始化,存在多个副本,各个对象拥有的副本互不影响

static成员变量初始化顺序按照定义的顺序来进行初始化

 

static块
构造方法用于对象的初始化。静态初始化块,用于类的初始化操作。

在静态初始化块中不能直接访问非staic成员。

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;
    }
}

  

自定义求平方数的静态方法示例:

package demo;

public class SquareInt {

	public static void main(String[] args) {
		int result;

		for (int x = 1; x <= 10; x++) {
			result = square(x);
			// Math库中也提供了求平方数的方法
			// result=(int)Math.pow(x,2);
			System.out.println("The square of " + x + " is " + result + "\n");
		}
	}

	// 自定义求平方数的静态方法
	public static int square(int y) {
		return y * y;
	}
}

  

结果

The square of 1 is 1

The square of 2 is 4

The square of 3 is 9

The square of 4 is 16

The square of 5 is 25

The square of 6 is 36

The square of 7 is 49

The square of 8 is 64

The square of 9 is 81

The square of 10 is 100

  

如果将子方法中的static去掉

会报错:Cannot make a static reference to the non-static method square(int) from the type SquareInt

原因:在main方法中没有实例化类对象,在访问非静态方法时,需要通过实例对象来访问,而在访问静态方法时,才可以直接访问

解决方法:可以实例化类对象

package demo;

public class SquareInt {

	public static void main(String[] args) {
		int result;
		SquareInt square = new SquareInt();
		for (int x = 1; x <= 10; x++) {
			result = square.square(x);
			// Math库中也提供了求平方数的方法
			// result=(int)Math.pow(x,2);
			System.out.println("The square of " + x + " is " + result + "\n");
		}
	}

	// 自定义求平方数的静态方法
	public  int square(int y) {
		return y * y;
	}
}

  

 

posted @ 2022-09-18 16:20  ashuai~  阅读(52)  评论(0)    收藏  举报