组团学

静态与唯一(static/final)

阅读 (983778)

1、static

1.1、static概述

static表示静态的意思,可以修饰变量、方法,还可以编写静态代码块。能够直接被类引用。

在我们平时的使用当中,static最常用的功能就是修饰类的属性和方法,让他们成为类的成员属性和方法,我们通常将用static修饰的成员称为类成员(类变量与类方法)或者静态成员(静态变量与静态方法)。

1.2、static应用

1.2.1、类变量

类变量就是用static修饰的成员变量。

class Student { private String name; private int age; // 学生的id private int sid; // 类变量,记录学生数量,分配学号 public static int numberOfStudent = 0; public Student(String name, int age){ this.name = name; this.age = age; // 通过 numberOfStudent 给学生分配学号 this.sid = ++numberOfStudent; } // 打印属性值 public void show() { System.out.println("Student : name=" + name + ", age=" + age + ", sid=" + sid ); } } public class StaticDemo01 { public static void main(String[] args) { Student s1 = new Student("张三", 23); Student s2 = new Student("李四", 24); Student s3 = new Student("王五", 25); Student s4 = new Student("赵六", 26); s1.show();// Student : name=张三, age=23, sid=1 s2.show(); // Student : name=李四, age=24, sid=2 s3.show(); // Student : name=王五, age=25, sid=3 s4.show(); // Student : name=赵六, age=26, sid=4 } }

运行结果:

image20200112003513927.png

1.2.2、类方法

static的另一个作用,就是修饰成员方法。相比于修饰成员属性,修饰成员方法对于数据的存储上面并没有多大的变化,因为我们从上面可以看出,方法本来就是存放在类的定义当中的。static修饰成员方法最大的作用,就是可以使用"类名.方法名"的方式操作方法,避免了先要new出对象的繁琐和资源消耗,我们可能会经常在帮助类中看到它的使用:

public class StaticDemo02 { public static void print(Object o){ System.out.println(o); } public static void main(String[] args) { StaticDemo02.print("Hello world"); } }

运行结果:

image20200111232241693.png

1.2.3、静态代码块

定义在类的里面方法的外面,随着类的加载而执行且执行一次,优先与main()和构造方法执行。

格式:

class A{ static{ } public void v(){} }
public class StaticDemo03 { static int x; static { System.out.println("静态代码块"); x = 12; } public StaticDemo03(){ System.out.println("构造函数"); } public static void main(String[] args) { new StaticDemo03().print(); } public void print(){ System.out.println(x); } }

运行结果:

image20200112011824633.png

2、final

2.1、final概述

在java中,final的含义在不同的场景下有细微的差别,但总体上来说,它指的是“这是不可变的”。

2.2、final应用

2.2.1、修饰类

都是被final修饰的类,目的就是供我们使用,而不让我们所以改变其内容。

final class T{//T为一个功能类,Scanner\Random public void t(){ System.out.println("T"); } } public class FinalDemo01 extends T {//不能被继承 public static void main(String[] args) { } }

2.2.2、修饰方法

final修饰的方法,不能被重写

class T { public final void t() {//final修饰的方法是唯一的 System.out.println("T"); } } public class FinalDemo01 extends T { public void t() {//不能被重写 System.out.println("FinalDemo01"); } public static void main(String[] args) { } }

2.2.3、修饰变量

成员变量

被final修饰的成员变量是一个常量,叫符号常量。一般都有书写规范,所有字母都大写

class A{ final double PI=3.1415926; }

局部变量

声明的变量是唯一的不能重新赋值。

public class FinalDemo02 { public static void main(String[] args) { // 声明变量,使用final修饰 final int a; // 第一次赋值 a = 10; // 第二次赋值 a = 20; // 报错,不可重新赋值 // 声明变量,直接赋值,使用final修饰 final int b = 10; // 第二次赋值 b = 20; // 报错,不可重新赋值 } }
需要 登录 才可以提问哦