java basics about final keyword

2019-03-30 05:19发布

Can final keyword be used for a method?

8条回答
ゆ 、 Hurt°
2楼-- · 2019-03-30 05:51

Yes.

You can make a method final

public class A {
   public static final void f() {
      System.out.println("test");
   }
}

There are typically two reasons for making a method final

  1. When a method is final, it "may" be inlined.
  2. When a method is final, the method is impossible to override.
查看更多
Fickle 薄情
3楼-- · 2019-03-30 05:55

Absolutely! The final keyword can be applied to just about anything, in each case meaning "you don't get to change this anymore."

Here's what it means when applied to...

a variable: You simply cannot assign the variable a new value (rendering it a constant, of course)

a method: You cannot re-implement (i.e., override) this method in a subclass

a class: You cannot define a subclass

In each case we're simply indicating: once this thing is declared, this is the last value (or implementation) you'll ever see for it.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-03-30 06:00

Sure, check out The Final Word on the Final Keyword

public abstract class AbstractBase
{
    public final void performOperation()    // cannot be overridden
    {
        prepareForOperation();
        doPerformOperation();   
    }

    protected abstract void doPerformOperation();    // must override
}
查看更多
▲ chillily
5楼-- · 2019-03-30 06:02

Yes.

A final method cannot be overridden by subclasses. This is often used to prevent subclasses from altering crucial behaviors of the class.

查看更多
你好瞎i
6楼-- · 2019-03-30 06:02

yes, final keyword can be used for a method. It will preserve the immutability. it prevents between methods from being broken. For example, suppose the implementation of some method of class X assumes that method M will behave in a certain way. Declaring X or M as final will prevent derived classes from redefining M in such a way as to cause X to behave incorrectly.

查看更多
一纸荒年 Trace。
7楼-- · 2019-03-30 06:09

As a note to the other answers. You can use final. In practice I rarely see people using it and I'm not sure why.

A lot of the code I write these days is intended for multi-threaded environments and I tend to make the class final an immutable (if its a value class) so that it is threadsafe.

The problem with marking some methods as final (and not others) is that you are stating that there is something special about that method and nothing special about the others. That's rarely what people actually mean in my experience.

If a class is intended for inheritence you need to keep it clean and keep it small to prevent unwanted side-effects. All this depends on whether you are writing code for your self and your team or whether you are writing for a wider audience - i.e. a public api on an Open Source project or a commercial project.

查看更多
登录 后发表回答