Header

Wednesday 4 September 2013

IGNOU BCA 4th sem Solved Assignment - Differentiate the following and support with example: Final and static member

Differentiate the following and support with example:
Final and static member
Ans
The final keyword is used to create constants, i.e. data which is always for reading and never needs to change, once initialized. A simple example would be MaxAge, in a software to manage details of employees in a company. Lets say the maximum age of retirement is 60, so we know that no employee can have age greater than 60. So I will write –

final int MaxAge = 60;

Now anywhere in other part of software I can use the value simply for validation as follows:

If (age > MaxAge) // age is already declared somewhere as int
System.out.println(“There is an error. Invalid Age.”); // Oops error in age!

The static keyword is used to create variables which are shared by all instances (objects) of the class. The scope of usage of such a variable is class, i.e. it can be accessed only with the class unless it is declared public. Their lifetime is same as that of the program, which means they always exist and you don't need to create object to access them. A good example can be a variable to count the total number of errors in a class and its objects. The following is one example:

static int TotalErrors = 0;

Then we can write anywhere code like the following –

If (age > MaxAge)
{
System.out.println(“There is an error. Invalid Age!”);
TotalErrors++; // There was an error so increment it
}

Did that make any sense?
Actually I am a C++ guy, so if it did not make any sense, just forgive me. I tried my best. =)


@To XTremeHell [In response to his assertion that const and final are different]

Sorry sir, you need to go back to read the textbooks again. Java's "final" and C++ "const" are indeed ABSOLUTELY same. The value of const need not be known at compile time. See the C++ code below:-

int var = 0;
DoSomethingWithVar(&var); // The function modifies var.
const int myReadOnlyValue = var;

The point is "myReadOnlyValue" is a constant. Now can you tell me XTremeHell, how the compiler is supposed to know the value of myReadOnlyValue, even though it is a constant?

Static variables are marked final.
Static method can't be instantiated.
Static method can't be overloaded & overridden.

Final variable can't be modified.
Final variables are implicitly final.
Final methods can't be overriddern.
Final class can't be subclassed.

No comments:

Post a Comment