aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Final fields(Static & Instance) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Final fields(Static & Instance)" Watch "Final fields(Static & Instance)" New topic
Author

Final fields(Static & Instance)

Tushar Kansara
Ranch Hand

Joined: Aug 14, 2000
Posts: 38
The process of declaring a clas Final would no doubt dis allow any of its, class methods(Read Static)& Instance methods not to be overridden. But I am not sure about, The variables.
Say I have an static variable in a class declared final, can it be changed, when i am using an instance of the class & try to change the value in the variable. What about instance variables that have declared within the final class.
Regards
Tushar Kansara
------------------
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
If a class is final, all the methods in it r final. There is no other way because a method in a final class cannot be overridden since there is no subclasses for that class at all.
But a final class can have non-final instance or static variables. Try this code:
final class T {
static int i;
int k;

public static void main(String args[]) {
i = 10;
System.out.println("static non-final : " + i);
T t = new T();
t.meth();
}
public void meth() {
k = 20;
System.out.println("non-final instance var : " + k);
}
Tushar Kansara
Ranch Hand

Joined: Aug 14, 2000
Posts: 38
Thanx for the clarification. Lot seems to be clear.
Only one thing with reference to above code,
I am assuming that since Class T is final, I would nt be able to sub class the Class T to put in different values in Instance as wells as Static variables.
Regards
Tushar Kansara
kiran bayyana
Greenhorn

Joined: Aug 15, 2000
Posts: 17
In my post above, I didn't mean u cannot create instances of class T and cannot change its instance variables. We CAN create instances of a final class and change the values of its instance vars. We just cannot subclass the final class, so the methods in it cannot be overridden. Just get out of ur confusion of creating instance and creating subclass.
Tushar Kansara
Ranch Hand

Joined: Aug 14, 2000
Posts: 38
Yes I am clear on Difference in Instance of a class & creating sub class of a class are two different issues.
Thanx for the clarification.
Regards
Tushar Kansara
------------------
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Final fields(Static & Instance)