1、final 修饰的局部变量只能被赋值一次 2、final 修饰的成员变量只能被赋值一次,并且必须在声明时就赋值 3、final 修饰的基本类型变量是一个常量(只能被赋值一次),引用类型变量不可修改地址,如对象 4、final 修饰的方法不能被重写 5、final 修饰的类不能被继承 package com.fc.j._final; /* * final修饰的局部变量 */ public class FinalDemo1 { public static void main(String[] args) { // 测试final修饰的修饰的变量 final int num;
num = 10;
System.out.println(num);
/* * 被final修饰的变量只能赋值一次 * * The final local variable num may already have been assigned * * 被final修饰的局部变量num可能已经被赋值 */ // num = 20; } }
// final修饰的类不能被继承,断子绝孙 class Father { /* * final 修饰的成员变量必须在声明时就赋值 * * The blank final field age may not have been initialized * 空白的final成员变量可能未被初始化 */ // final int age; final int age = 16;
public final void play() { System.out.println("下棋"); } }
class Son extends Father { /* * Cannot override the final method from Father * 无法重写被final修饰的方法 */ // @Override // public final void play() { // // } }
特点
final 修饰可以保证安全性,比如数组的长度属性,String 类,这些都是 final 修饰的,保证不可变
publicclassPersonDemo{ publicstaticvoidmain(String[] args){ Person person1 = new Person("张三", 16); Person person2 = new Person("李四", 17); Person person3 = new Person("王五", 18); Person person4 = new Person("赵六", 19);
/* * The static field Person.address should be accessed in a static way * 静态成员变量应该通过静态的方式访问(注意这里是应该,不是必须) * * Change access to static using 'Person' (declaring type) * 使用Person声明类型来更改对静态的访问 * 通过类名来操作成员变量:Person.address */ System.out.println("姓名:" + person1.name + " 年龄:" + person1.age + " 地址:" + Person.address); System.out.println("姓名:" + person2.name + " 年龄:" + person2.age + " 地址:" + Person.address); System.out.println("姓名:" + person3.name + " 年龄:" + person3.age + " 地址:" + Person.address); System.out.println("姓名:" + person4.name + " 年龄:" + person4.age + " 地址:" + Person.address);
/* * Cannot make a static reference to the non-static field Person.name * * 将name添加static后没有报错 */ // System.out.println("没有对象:" + Person.name);
/* * 通过对象调用statice修饰的成员方法 * * The static method test() from the type Person should be accessed in a static way */ // person1.testStatic();
// 通过类名直接调用静态方法 Person.testStatic(); } }
总结
1 2
1、通过类名调用静态成员变量,因为静态变量与对象无关 2、静态变量被所有对象共享,一处更改处处更改
static 方法
static 方法一般称作静态方法,由于静态方法不依赖于任何对象就可以进行访问,因此对于静态方法来说,是没有 this 的,因为它不依附于任何对象,既然都没有对象,就谈不上 this 了。并且由于这个特性,在静态方法中不能访问类的非静态成员变量和非静态成员方法,因为非静态成员方法/变量都是必须依赖具体的对象才能够被调用。
// 自定义static修饰的成员方法 publicstaticvoidtestStatic(){ /* * 静态方法不能调用非静态方法 * Cannot make a static reference to the non-static method test() from the type Person */ // test(); System.out.println("static mothed");
/* * 不能再静态方法中使用this关键字 * * Cannot use this in a static context */ // this.name; }