Final Variables


Final Variables

A final variable is one whose value, once it is set, cannot be changed. Final variables are designated as such by using the final keyword in the variable declaration. Both instance and class variables can be declared final . Final variables are useful for defining constants that have public access but whose values aren't meant to be changed.

Example: Using Final Variables

One problem with the BlackBody class from the "Using Instance and Class Variables" example earlier in this chapter is that since the class variable SIGMA has public access the value of it can be changed. If a user were to change the value of the Stefan-Boltzmann constant, it would have an adverse effect on the accuracy of a radiative heating calculation. To prevent this, the variable SIGMA can be declared to be final .

[View full width]
 
[View full width]
public class BlackBody3 { public static final double SIGMA = 5.6697e-12; private double temperature, emissivity; public BlackBody3(double emiss, double t) { emissivity = emiss; temperature = t; } public double getTemperature() { return temperature; } public double getHeating() { return SIGMA*emissivity*Math.pow(temperature,4.0); } } The BlackBody3Driver class creates a BlackBody3 object. Because the variable SIGMA is now graphics/ccc.gif final, any attempts to change its value will cause a compiler error. public class BlackBody3Driver { public static void main(String args[]) { BlackBody3 body = new BlackBody3(0.85, 1000.0); // This statement won't compile // BlackBody3.SIGMA = 4.0e-12; double qDot = body.getHeating(); System.out.println("heating rate is "+qDot); } }

Output ”

 heating rate is 4.819245000000 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net