Analysis of final finally finalize differences

  • 2020-04-01 02:16:43
  • OfStack

1. The final
Final modifies a class, which cannot be inherited, as a top-level class.
Final modifies a variable, indicating that the variable is constant.
The final modifier means that the method cannot be overridden, but can be overridden in the final method.

For example, there is a base class Person,in which there is a public final void eat() method, you can overload the method with the same name in the Person class, such as public void eat(String name,int age). If you have a subclass Student, you can override non-final methods of the parent class in Student, but you cannot override final methods.

The Person


package test2;
public class Person {
    private String name;
    private int age;

    public final void eat()
    {
        System.out.println("this is in person class");
    }

    public void eat(String name,int age)
    {

    }

}

Student

package test2;
public class Student extends Person {
    @Override
    public void eat(String name, int age) {
        // TODO Auto-generated method stub
        super.eat(name, age);
    }
}

The common final methods are the wait() and notify() methods in the Object class.

2. The finally
Finally is the keyword, and in exception handling, the try clause executes what needs to be run, the catch clause catches the exception, and the finally clause means that the exception is executed regardless of whether or not it occurs. Finally is optional. But try... Catch must come in pairs.

3. The finalize ()
Finalize () method name, the method of the Object class, Java technology allows you to use finalize() methods to do the necessary cleanup before the garbage collector clears the Object from memory. This method is called by the garbage collector when it determines that the object is not referenced. A finalize() method is a subclass called on an object before it is removed by the garbage collector to override a finalize() method to tidy up system resources or perform other cleanup operations.

Code example:


class Person
{
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String toString()
    {
        return " Name: "+this.name+" Age: "+this.age;
    }

    public void finalize() throws Throwable{//Object free space is called by default for this method
        System.out.println(" Object is released -->"+this);//Output the secondary object directly, calling the toString() method
    }

}
public class SystemDemo {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Person per=new Person("zhangsan",30);
        per=null;//Disconnect the reference and free up space
        //Method 1:
        System.gc();//Forced release space
        //Method 2:
//        Runtime run=Runtime.getRuntime();
//        run.gc();
    }
}


Related articles: