aspose file tools*
The moose likes Java in General and the fly likes methods that are static AND final Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "methods that are static AND final" Watch "methods that are static AND final" New topic
Author

methods that are static AND final

paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20693
    ∞

I just came across a patch of code where all of the methods are static <i>and</i> final. Looking through source control history shows a point where they were just static and somebody painstakingly went through the code and added "final" to every method.
Since a static method cannot be overridden, and final is supposed to forbid overriding of a method, why declare the method static and final?


permaculture Wood Burning Stoves 2.0 - 4-DVD set
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
Hi Paul:
That is pretty wired to me. But to change all the 'static' to 'static final' may not be that diffcult. I can recall in one of the IDE(forget which language?) I used before, you can change it like in spell checker.
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
Maybe Emacs? :roll:
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
In fact, I have done something similar before. To change 'static' to 'static final', people should substitute ' static ' with ' static final ', notice the space before and after the string, the goal is to eliminate the possibility of 'static' string inside another string. It works out pretty well.
Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
Paul,
What are you talking about? I'm not sure I follow. Try the following:
Compile this:

You'll find it compiles with no problem and runs as one might expect.
Now compile this:

It throws the error:
TestStatic.java:24: print() in Sub cannot override print() in Base; overridden method is static final
public static void print()
You can override a static, but not a final static.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Well, Robert's code reaffirms that the people who wrote the compiler error messages don't always understand the language specification. :roll: That is, the compiler is performing correctly, but the reason it gives is incorrect. You can't override a static method, period. However you can do something that looks like it, which is called shadowing. (The difference is, there's no dynamic runtime method lookup for static methods.) I don't know why the JLS bans shadowing of final methods, but it does. So final does have an effect here, though a minor one. Perhaps the coder who put in "static final" really wanted to prevent shadowing. That's not a bad idea actually - it prevents people from thinking they've overridden a method, when in fact they have not. It's also possible that "static final" was put there by a programmer who thought static methods really could be overridden, and so they mistakenly thought they should prevent it.
[ January 29, 2003: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
Jim,
Can you provide a deeper explanation of how shadowing works? I mean, what exactly does it mean that I haven't overridden the static method? In what cases will shadowing act differently than overriding?
Mathews P Srampikal
Ranch Hand

Joined: Nov 26, 2002
Posts: 211
Hi Robert,
As you have given an example there. i will make you more clear about the overring and static final.
What you have to do is
1. Run the program as it is and note the output.
2. add 2 line in the main mathod namely
base=sub;
base.print();
Now Run the proram and note the output.Are you getting any benefits of overring here???. I say NO as the output is Base.Print.Becuse at the time of compilation itself it knows which method has to be executed.
3. Do the same 2 line of code and remove the static from Base and Sub
Now run the program and see the Result...Here You are getting intended output as Sub.Print
:roll:


Thanks,
Mathews
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Also, here are the JLS definitions of overriding and hiding. More discussion can be found by searching for these terms in (probably in JiG intermediate or advanced) - this one seems to cover most of it.
Sorry I was a little testy because I think the compiler developers should know better - that crappy error message has been with us for ages. But for the rest of us, it's easy to get confused. In fact the more I think of it, the more I believe that making all static methods final is a good idea. Prevents anyone from accidentally shadowing a method without realizing it. Can anyone come up with an example where shadowing a static method is a good thing? I think any problems with making static methods final can be easily resolved at compile time by changing the method name - and being forced to do this avoids any unnecessary confusion later, IMO.
Rams Senthiil
Greenhorn

Joined: Jan 29, 2003
Posts: 12
Sataic methods can be overriden or atleat you can make your class behave so
example
class x{
public static stat(){
System.out.println("Base class");
}
}
class y extends x{
public static stat(){
System.out.println("derived Class");
}
public static void main(String arg[]){
stat() // prints derived class
}
}
suppose you comment stat() method in class y it prints stat() method in base class. Suppose you declared stat() in class x as final and if you try to use same signature of method in y would result in error message.
Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
Jim,
I can't think of a specific example off the top of my head but...
What about a situation where you have a class B that needs the extend class A in order to work as a handler in some container AND in order to do something else ( in the container or whatever) it needs to implement a static method that happens to have the same signature as class A. If the compiler didn't allow shadowing here, you'd be in a major bind.
Mathews P Srampikal
Ranch Hand

Joined: Nov 26, 2002
Posts: 211
Rams Hold on. As you Said,
<b>Sataic methods can be overriden or atleat you can make your class behave so</b>
This is wrong.You can do this But behaviour will be different.static means it will find out the method at the time of Compilation.There is nothing to do with the overriding.... See the code as you have given
class x{
public static stat(){
System.out.println("Base class");
}
}
class y extends x{
public static stat(){
System.out.println("derived Class");
}
public static void main(String arg[]){
stat() // prints derived class
}
}
//
Now I am going to change the main method..
public static void main(String arg[]){
x X=new x();
y Y=new y();
X.stat(); // prints base class
Y.stat(); // prints derived class
//Now
X=Y;
X.stat(); //Check the Result
//Now you remove the static word from x and y class and run it and see the difference..

}
:roll:
Rams Senthiil
Greenhorn

Joined: Jan 29, 2003
Posts: 12
Of course Mathew it will work even if you type baseclassname.Staticmethod().I have written this smaple to clarify that base class static method can be duplicated in derived class provided the base class static method dosent qualify with final keyword.
Mathews P Srampikal
Ranch Hand

Joined: Nov 26, 2002
Posts: 211
You can do it.But it is not overriding as there is no impact onoverriding it(It is Just like giving the same name signatures in case if the method is static).What I am telling you is it is not having any benefit of overriding
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

a final method can not be overridden.
a final variable can not be reassigned.
So it was valid to add final to all the static variables you saw. It lets the next traveler know that they are meant to stick with their original values. lets the compiler know as well.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
a final method can not be overridden.
[sigh...]
A final nonstatic method can not be overridden.
A static method can not be overridden, but it may be hidden.
A final static method can not be hidden either.
Not sure what variables have to do with this topic - I thought we were dealing with methods. But anyway...
What about a situation where you have a class B that needs the extend class A in order to work as a handler in some container AND in order to do something else ( in the container or whatever) it needs to implement a static method that happens to have the same signature as class A. If the compiler didn't allow shadowing here, you'd be in a major bind.
Why does it "need to implement" a static method with a particular signature? Not in order to implement an interface, since those only require you to implement non-static methods. And not in order to implement an abstract method from an inherited abstract class, since it's quite impossible to declare a static abstract method. The only reason I can think of why you might "need" to implement a static method with a particular name and signature is if someone wants to use a particular name. I think the appropriate response here is to tell that person that no, naming a static method the same name as a superclass method is a Bad Idea, if only because it will confuse people needlessly when they think they're calling one, and they're really calling the other. Just change the name to something different.
Alternately, if someone really insists on reusing the method name in a subclass, you can check out the base class file and remove the "final" keyword. But at least by having the final in there initially, you prevent anyone from accidentally reusing the name. It's a useful safety net; if someone wants to work without it, that's OK too.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
All the confusion about hiding static methods could have been avoided very easily... don't allow you to use an object reference to run a class method!!! Static methods should be run with a class name not an object reference. C# doesn't allow you to use an object reference to run static methods and that makes this whole confusing issue go away. This generates at least one thread a week in Prog Cert asking about overriding static methods!!!
Anyway, the one point that I didn't see raised that explains the difference between overriding and hiding... static methods aren't polymorphic so they can't be overridden, only hidden. They are assigned at compile time so when you use an object reference to run a static method it will run the static method using the class type of the reference not the class type of the object that the reference is pointing to. Is that confusing enough? I would explain it more simply but this is JiG(Advanced).
[ January 30, 2003: Message edited by: Thomas Paul ]

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
All the confusion about hiding static methods could have been avoided very easily... don't allow you to use an object reference to run a class method!!!
Amen, brother Thomas! I'm guessing they were still too C/C++ influenced when they made Java, and some people were maybe thinking of static methods as though they were merely non-virtual methods. Or maybe they were just on crack. Too late to change now though. At least "static final" prevents some misuses of the language.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Thomas Paul:
All the confusion about hiding static methods could have been avoided very easily... don't allow you to use an object reference to run a class method!!! Static methods should be run with a class name not an object reference. C# doesn't allow you to use an object reference to run static methods and that makes this whole confusing issue go away.

Interesting - doesn't this unnecessarily produce a lot of broken code when you change an instance method to become a static method?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Originally posted by Ilja Preuss:
Interesting - doesn't this unnecessarily produce a lot of broken code when you change an instance method to become a static method?

It's a change to the interface so broken code should be expected. The only circumstance where a method should go from instance to static is if the API was poorly written in the first place.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Thomas Paul:
It's a change to the interface so broken code should be expected. The only circumstance where a method should go from instance to static is if the API was poorly written in the first place.

Well, I like to state this more positive - it's when you learned something about the code. And I'd like the language to hinder me as little as possible putting that new knowledge into the code - or so I think at the moment.
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20693
    ∞

Thanks guys. This now makes sense.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Originally posted by Ilja Preuss:

Well, I like to state this more positive - it's when you learned something about the code. And I'd like the language to hinder me as little as possible putting that new knowledge into the code - or so I think at the moment.

There's a really good reason for not changing an instance method to a static method... you are screwing anyone who has extended your class and overridden your formerly instance method. Now that application doesn't work or compile.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
If you've published the API to other parties outside your control, then yes, I agree completely. But in many cases all code associated with a given project is checked into source control and you at least have access to it (and often authority to change it if necessary). It may be perfectly reasonable to change a method from nonstatic to static (or vice versa) as your understanding of the project evolves. And it's fairly easy to do, since making the method final will allow you to easily detect (by recompiling the entire project) if any other code in the project is overriding or shadowing the method. Of course if it is, you may well decide you can't perform this refactoring. Or you may find a way to rewrite the other code to avoid the need to override/shadow the method.
[ January 31, 2003: Message edited by: Jim Yingst ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: methods that are static AND final