Is it easy to write an essay? It’s not easy. First of all, you need a quiet environment, which is not easy. Many of my friends’ offices are open and noisy. Besides, if I write during working hours, my boss will not be happy. I have to find time to write. Second, the environment, but also have a quiet heart, if the mind of other lingering things, that is bad, sitting in front of the computer all day will not achieve results.

I admire some of my colleagues very much. They write ten thousand words long, which, in my opinion, is almost impossible to accomplish. Because I want to day more, ten thousand word long article, if go original words, need at least a week, even a month time.

As you can see, my articles can be read within five minutes, and I can ensure that you can learn or review some knowledge after reading. This is my style, easy to understand, light humor.

Well, here comes another article in my last series: You still can’t use the final keyword.

It’s already 9:30pm and I haven’t got off work yet, because I have to fix a bug with Xiao Wang. I ordered a supreme pizza, and while eating with relish with Xiao Wang, he suddenly asked me a question: “Boss, could you tell me the key word of final in detail? I always feel that my cognition of this key word is not comprehensive enough.”

Suddenly my anger came, although wang asked the attitude is very humble, very humble, but I still couldn’t help but scold: “I wipe, Wang, your ya unexpectedly won’t use final, I was how to interview you come in!”

When I get angry, I still have principles. When I got home at half past ten, I decided to write an article for Xiao Wang, explaining the final keyword carefully, hoping to help more friends.

Although inheritance allows us to reuse existing code, there are times when we really need to limit extensibility for some reason, and the final keyword can help us do that.

01, final class

If a class uses the final keyword modifier, it cannot be inherited. If you look carefully, Java has many final classes, such as the most common String class.

public final class String
    implements java.io.Serializable.Comparable<String>, CharSequence.Constable.ConstantDesc {}
Copy the code

Why is the String class designed to be final? There are three reasons for this:

  • To implement a string constant pool
  • For thread safety
  • For immutability of HashCode

For more details on why, check out an article I wrote earlier.

Any attempt to inherit from a final class will result ina compilation error. To verify this, let’s look at the following example, where the Writer class is final.

public final class Writer {
    private String name;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

If you try to inherit it, the compiler will tell you that the Writer class is final and cannot be inherited.

However, just because a class is final does not mean that its objects are immutable.

Writer writer = new Writer();
writer.setName("Silent King II.");
System.out.println(writer.getName()); // The King of Silence
Copy the code

The default value of Writer’s name field is NULL, but it can be changed to Silent King ii via settter method. That is, if a class is only final, it is not all that is immutable.

If you want to know the whole truth about immutable classes, check out my previous post about immutable classes. Suddenly, I realized that writing a series of articles is really good, so many related concepts are covered. I really surprised myself.

There are security reasons for making a class final, but this should not be done intentionally, because defining a class as final means that it cannot be inherited, and if there are problems with some of the class’s methods, we cannot rewrite them to fix them.

02. Final methods

Methods decorated with final cannot be overridden. If we’re designing a class and we think that some method shouldn’t be overridden, we should make it final.

The Thread class is an example. It is not final itself, which means we can extend it, but its isAlive() method is final:

public class Thread implements Runnable {
    public final native boolean isAlive(a);
}
Copy the code

It is important to note that this method is a native method used to verify that the thread is active. The local method is determined by the operating system, so overriding it is not easy.

The Actor class has a final method show() :

public class Actor {
    public final void show(a) {}}Copy the code

When we try to override this method, we get a compilation error:

If certain methods ina class are called by other methods, consider that the method being called is final; otherwise, overwriting the method will affect the use of the calling method.

What is the difference between a class that is final and a class that is not final, but all of its methods are final?

One thing I can think of is that the former can’t be inherited, which means methods can’t be overridden; The latter can be inherited and appended with non-final methods. Is it all right? Look how smart I am.

03. Final variables

Variables modified by final cannot be reassigned. In other words, a final variable, once initialized, cannot be changed. I was asked by a friend before, what is effective final and what is final? I have also explained this point in the previous article, so here is the address:

www.itwanger.com/java/2020/0…

1) The base data type of the final modifier

To declare a final variable of type int:

final int age = 18;
Copy the code

Try changing it to 30 and the compiler gets angry:

2) Final modifier reference type

We now have a normal Pig class that has a field name:

public class Pig {
   private String name;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

Declare a final modified Pig object in the test class:

 final Pig pig = new Pig();
Copy the code

The compiler also gets angry if it tries to reassign pig:

We can still modify the Pig field:

final Pig pig = new Pig();
pig.setName("Maverick");
System.out.println(pig.getName()); // Be a maverick
Copy the code

3) final

Final fields can be static or non-static, as in the following:

public class Pig {
   private final int age = 1;
   public static final double PRICE = 36.5;
}
Copy the code

Non-static final fields must have a default value, otherwise the compiler will warn that there is no initialization:

Static final fields, also called constants, should have uppercase names and can be initialized at declaration time or through static code blocks.

  1. Final modifier

The final keyword can also modify parameters, which means that parameters cannot be modified within the method body:

public class ArgFinalTest {
    public void arg(final int age) {}public void arg1(final String name) {}}Copy the code

If you try to modify it, the compiler prompts the following error:

04,

Dear readers, have I been thorough? I think Xiao Wang will thank me for my kindness after reading this article. After all, he is an active and studious colleague.

If you feel that the article is helpful to you, please search wechat “Silent King ii” for the first time to read, reply to “concurrency” there is a rewrite of Ali Daniel Java concurrent programming actual combat, from now on no longer need to worry about the interviewer in this aspect of difficulties.

GitHub, portal ~, GitHub, portal ~, GitHub, Portal ~

I am the Silent King 2, a programmer with good looks but mediocre talent. Attention can improve learning efficiency, don’t forget three even ah, like, collect, message, I don’t pick, hee hee.