聊一聊关键字---final与static

来源:互联网 发布:js删除节点 编辑:程序博客网 时间:2024/05/21 20:55

首先,我们需要知道final这个词是什么意思,英文解释如下:

final   :   adj.最终的,不可更改的

在Java中,final代表的要是最终,可以称之为完结器.我们可以用它来声明属性,方法或类.

使用final声明需要注意以下几点:

1.声明的类不能有子类

2.声明的方法不能被子类覆写

3.声明的变量是常量,不可更改,且要求全部字母大写(常常用final+static来声明全局常量)


接下来,看看static

static   :   adj.静态的

先看看static声明的属性:如果程序中用static声明属性,则此属性称为全局属性,那么它有什么用呢?我们先来看一段代码:

class Person{String name;int age;String country = "A城";public Person(String name, int age) {this.name = name;this.age = age;}public void info(){System.out.println("姓名: "+this.name+" ,年龄: "+this.age+" ,城市: "+this.country);}}public class Test{public static void main(String []args){Person p1 = new Person("张三",30);Person p2 = new Person("李四",35);Person p3 = new Person("王五",40);p1.info();p2.info();p3.info();}}

此程序输出为:

姓名: 张三 ,年龄: 30 ,城市: A城
姓名: 李四 ,年龄: 35 ,城市: A城
姓名: 王五 ,年龄: 40 ,城市: A城

注:以上代码为了观看方便,没有进行封装.
问题来了,如果现在我不想叫A城了,改叫B城,但是已经产生了5000个对象,那我岂不是要一个一个这样去改?

p1.country="B城",p2.country="B城",p3.country="B城".....pn.country="B城"..

此时,我们需要把country当作是全局变量来处理,只要任何一个地方改了,那么其他读取它的地方也就改了

只需要把属性声明改成:

static String country = "A城";
即可.

这样,我们有以下测试代码:

class Person{String name;int age;static String country = "A城";public Person(String name, int age) {this.name = name;this.age = age;}public void info(){System.out.println("姓名: "+this.name+" ,年龄: "+this.age+" ,城市: "+this.country);}}public class Test{public static void main(String []args){Person p1 = new Person("张三",30);Person p2 = new Person("李四",35);Person p3 = new Person("王五",40);System.out.println("修改之前------------------------");p1.info();p2.info();p3.info();System.out.println("修改之后------------------------");p1.country="B城";p1.info();p2.info();p3.info();}}
程序输出为:

修改之前------------------------
姓名: 张三 ,年龄: 30 ,城市: A城
姓名: 李四 ,年龄: 35 ,城市: A城
姓名: 王五 ,年龄: 40 ,城市: A城
修改之后------------------------
姓名: 张三 ,年龄: 30 ,城市: B城
姓名: 李四 ,年龄: 35 ,城市: B城
姓名: 王五 ,年龄: 40 ,城市: B城

其实,在修改country时,我们最好利用类来对他进行修改,而不是具体的对象:

即应该把p1.country改成Person.country


再看看static声明的方法

用static声明的方法一般称之为类方法

class Person{String name;int age;static String country = "A城";public Person(String name, int age) {this.name = name;this.age = age;}public void info(){System.out.println("姓名: "+this.name+" ,年龄: "+this.age+" ,城市: "+this.country);}public static void all(){System.out.println("这是类方法");}}public class Test{public static void main(String []args){Person p1 = new Person("张三",30);Person p2 = new Person("李四",35);Person p3 = new Person("王五",40);p1.info();p2.info();p3.info();p1.all();Person.all();}}
需要注意的是,因为static声明的东西在编译时就需要确定,所以一般方法可以调用static声明的属性和方法,反之则不行!

说到这里,我们就提一下main方法

一个方法要被主方法调用,必须采用如下声明:

public static 返回值类型 方法名称(参数列表){}

之所以这样,是因为主方法是静态方法,它是不能调用非静态方法的!






































0 0