私有静态最终字段 [英] private static final fields

查看:190
本文介绍了私有静态最终字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想澄清一下。有什么区别 -

I just would like to clarify this. What is the difference between -

private static int STUDENT_AGE = 18; 

private static final int STUDENT_AGE = 18; 

在该字段内?

Jon Skeet解释为根本与某个特定实例无关,好吧我想我明白了。那么最终在这种情况下究竟做了什么呢?

Jon Skeet explained as "not related to a particular instance at all", ok I think I understand it. Then what does final do in this case exactly?

下面的代码不起作用是因为学生年龄被指定为静态最终?这是否意味着默认年龄根本不能被覆盖?那么是否可以创建指定非默认年龄的构造函数?

Below code does not work is it because student age is assigned as static final? Does it mean the default age can not be overwritten at all? then is it possible to create the constructor that specify an age other than the default?

private String myName;
private String myAddress;
private int myYearEnrolled;
private String myGender; 
private static final int STUDENT_AGE = 18; 

public Student(String name, String address, int year, String gender) {
    myName = name;
    myAddress = address;
    myYearEnrolled = year;
    myGender = gender; 
}

   public Student(int age)
{
     STUDENT_AGE = age; 
}


推荐答案

声明变量后 final ,其值不能在以后更改。在您提供的代码示例中,声明了一个常量,用于定义特定活动的学生年龄。这可能意味着将存在某种活动的条件,即将学生的年龄与此常数进行比较。如果学生年龄大于18岁,那么只允许他继续学习。

Once a variable is declared final, its value cannot be changed later. In the code sample you provided, a constant is declared for defining the age of a student for a particular activity. It might mean that there will be a condition where for certain activity, the age of the student will be compared with this constant. If the age of student is greater than 18, then only he will be allowed to proceed or not.

这篇关于私有静态最终字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆