Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final fields(Static & Instance)

 
Tushar Kansara
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
------------------
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic