Java Basics _ Analysis Java new,this,super,final keyword __ storage

Source: Internet
Author: User
A brief analysis of new,this,super,final keywords in Java New Keyword

For example people person=new people ();

create an object what does it do in memory? load the People.class file at the specified location on the hard disk into memory first. When executing the main method, the Main method's space (stack-stack) is opened in stack memory, and a variable person is assigned to the stack area of the main method. Creates an entity space in the heap memory and assigns a memory address value. The spatial allocation of attributes is performed in the entity space and is initialized by default. Displays initialization for the properties in the space. Initializes the construction code block for the entity. Call the entity's corresponding constructor to initialize the constructor function. () assigns the first address to person, and the person variable refers to the entity. (Point to the object) simply draw a diagram to help understand.

Final key word

The final modification to the base type indicates that the modified variable is constant and cannot be modified. A field that is both static and final means that it occupies only a certain amount of storage space that cannot be changed.

Final makes the application constant when used for object application. Once a reference is initialized to an object, it cannot be pointed to another object.

Final method: One is to lock the method to prevent the inheriting class from modifying its meaning, and to ensure that the behavior of the method remains unchanged in inheritance and is not overwritten. All private methods in a class are implicitly specified as final.

Final parameter: For a variable of the base type, this does not make any sense, because a variable of the base type is passed as a value when the method is invoked, which means that you can change the parameter variable in the method without affecting the calling statement, but it is useful for object variables. The object variable is passed its reference when passed. So your modification of the object variable in the method also affects the object variable of the calling statement, and when you do not need to change the argument in the method, the explicit use of final declaration will prevent you from inadvertently modifying the calling method.

Final class: When the whole of a class is defined as final, it indicates that the class has final properties and methods and is not allowed to be inherited, modified.

import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class          bat{final pi=3.14;            When defined, the value of final int i;        Because you want to initialize in the constructor, you cannot give the final list of values here;
        This variable is also the same as the above Bat () {i=100;
    List=new LinkedList ();
        } Bat (int ii,list l) {i=ii;
    List=l;
        public static void Main (string[] args) {bat b=new bat ();
        B.list.add (New Bat ());
        b.i=25;
        B.list=new ArrayList ();
        System.out.println ("i=" +b.i+ "List Type:" +b.list.getclass ());
        B=new Bat (23,new ArrayList ());
        B.list.add (New Bat ());
    System.out.println ("i=" +b.i+ "List Type:" +b.list.getclass ()); }
}

This program is a simple demonstration of final general usage. This gives you a little flexibility by using the method of initializing in a constructor here. As shown in the two overloaded constructors of bat, the first default constructor gives you the default value, and the overloaded constructor initializes the final variable based on the value or type you provide. But sometimes you don't need this flexibility, you just need to define the value and never change it, then don't use this method. In the main method, there are two lines of comment out, if you remove the annotation, the program will not be compiled, which means that, whether it is the value of I or the type of list, once initialized, it can not be changed. However, B can be reinitialized to specify the value of I or the type of list, which is shown in the output result:

i=100 list Type:class java.util.LinkedList
i=23 List type:class java.util.ArrayList

Another use is to define that the parameters in the method are final, for a variable of the base type, this does not make any sense, because a variable of the base type is passed as a value when the method is invoked, which means that you can change the parameter variable in the method without affecting the calling statement, but it is useful for object variables. , because the object variable passes its reference when it is passed, so your modification of the object variable in the method also affects the object variable in the calling statement, and when you do not need to change the object variable as a parameter in the method, the explicit use of final declaration will prevent you from inadvertently modifying the calling method.
In addition, when an inner class in a method uses a parameter variable in a method, the parameter must also be declared final before it can be used, as shown in the following code:

public class inclass{
   void Innerclass (Final String str) {
        class iclass{
            IClass () {
                System.out.println ( STR);
            }
        IClass ic=new IClass ();
    }
  public static void Main (string[] args) {
      inclass inc=new inclass ();
      Inc.innerclass ("Hello");
  }

Final Method

Declaring a method final means that you already know that the method provides functionality that satisfies your requirements, does not need to be extended, and does not allow any class inherited from this class to overwrite this method, but inheritance can still inherit this method, which means it can be used directly. There is also a mechanism called inline, it will allow you to insert the method body directly into the call place when you call the final method, instead of making routine method calls, such as saving breakpoints, pressing stacks, and so on, which may make your program more efficient, but when your method body is very large, Or if you call this method in more than one place, your calling principal code expands rapidly and may affect efficiency, so be careful to use final method definitions. Final Class

When you apply final to the class, you need to think about it, because a final class cannot be inherited by anyone, which means that this class is a leaf class in an inheritance tree, and that the design of this class has been considered perfect without any need for modification or extension. For a member of the final class, you can define it as final or not final. And for the method, because the class is final relationship, natural also become final type. You can also explicitly add a final to the method in the final class, but this obviously doesn't make sense.

The following program demonstrates the final method and the final class usage:

Final class final{
    final String str= "final Data";
    Public String str1= "non final data";
    Final public void print () {
        System.out.println (' final method. ');
    }
    public void What () {
        System.out.println (str+ "
" +str1);
    }
public class Finaldemo {   //extends final cannot inherit public 
    static void Main (string[] args) {
        final f=new final ();
        f.what ();
        F.print ();
    }

As you can see from the program, the final class is almost no different from the normal class, except that it loses its inherited attributes. The difference between final method and non final method is also difficult to see from the procedure line, just remember to use carefully.

The application of final in design pattern

In design mode, there is a pattern called invariant mode, in Java through the final keyword can easily implement this pattern, in the final member of the application of the program Bat.java is an example of the invariant mode. This and Super

One of the formal parameter names in your method has the same name as a member of the current object, and in order to avoid confusion, you explicitly use the This keyword to indicate that you want to use a member, and the method is this. The member name, and the one without this is the criminal ginseng. Alternatively, you can use this. Method name to refer to a method of the current object, but this is not necessary, and you can access that method directly using the method name.

When a method of a parent class is overridden, you can use super to invoke the method of the parent class. If the method of the parent class can be called by the Quilt class, you can use it like this, using the name of the member in the super. Parent class.

Super and this are immediately followed by the appropriate parameters, so its meaning has changed. A super parameter is used to invoke a constructor in the parent class that has the same form, and the parameter then invokes the constructor that currently has the same parameter.

This usually refers to the current object, and super usually refers to the parent class.

The JavaBean (coffee beans) in web development is based on this principle, which realizes the encapsulation of the data. Here's why you put this and super on the front

When you create an instance of a subclass, the constructor of the parent class is invoked first, and then the constructor of the subclass is called, and if there is no default constructor in the parent class, it must be called as shown in the constructor of the subclass (as in the following example).
The order in the program is this:

             Super (..... ///Parent class constructor ...        Current class constructor statement

In the same way, when there are multiple constructors in a class, other constructors can also be called in one of the constructors to initialize the object, which is called an "explicit constructor invocation", which executes the usual super () procedure and subsequent operations when the constructed method is called. Then in the execution of the construction statements in this constructor, this is the order:
This (...)//other constructors of the current class
..//Other statements of the current constructor

In fact, why do you want to put this (...) It's easy to understand, because any subclass must first call the constructor of the parent class, and when you use the "Show constructor call" to use this (...) When invoking other constructors of the current class, this time the parent class is constructed in this (...) Inside executed, this (...) It should include not only the construction of the current class, but also the construction of the parent class, so in order to ensure that the constructor of the parent class is executed first, you must first call this (...) Small Example

public class demothis{
  private String name;
  private int age;
  Demothis (String Name,int age) {
    setname (name);//You can add this to invoke the method, like this: This.setname (name), but this is not necessarily
    setage (age );
    This.print ();
  }   
  The public void SetName (String name) {
    this.name=name;//must indicate that you want to refer to the member variable
  } public
  void setage (int age) {
    this.age=age;
  }
  public void print () {
    System.out.println ("name=" +name+ "age=" +age);//This is not required in this line because there is nothing to cause confusion
  }
  public static void Main (string[] args) {
    demothis dt=new demothis ("Kevin", ")";
  }

This code is simple, and you should be able to see it without explaining it. In the constructor you see the This.print (), you can use print () to replace it, the effect is the same. Here we modify this program to demonstrate the use of super.

Class person{public
  int C;
  private String name;
  private int age;
  protected void SetName (String name) {
    this.name=name;
  }
  protected void Setage (int age) {
    this.age=age;
  }
  protected void print () {
    System.out.println ("name=" +name+ "age=" +age);
  }
public class Demosuper extends person{public
  void print () {
    System.out.println ("Demosuper:");
    Super.print ();
  }
  public static void Main (string[] args) {
    demosuper ds=new demosuper ();
    Ds.setname ("Kevin");
    Ds.setage ();
    Ds.print ();
  }

In Demosuper, the redefined print method repeats the Print method of the parent class, which first does its own thing, and then invokes the overridden method of the parent class. The output illustrates this point:

Demosuper:
Name=kevin age=22

The use of this method is more commonly used. In addition, if a member of the parent class can access the quilt class, you can use it like this, using the "member name in Super. Parent class," but often you do not access the member names in the parent class in this way.

In the constructor

A constructor is a special method that is invoked automatically when an object is initialized. In the constructor, this and super also have the various uses described above, and it has a special place, please see the following example:

Class person{public
  static void prt (String s) {
    System.out.println (s);
  }
  Person () {
    prt ("A person.");
  }
  Person (String name) {
    prt ("A person name is:" +name);
  }
Public class Chinese extends person{
  Chinese () {
    super ();  Invokes the parent class constructor (1)
    prt ("A Chinese."); /(4)
  }
  Chinese (String name) {
    super (name);//Invoke constructor function (2) PRT with the same formal parameters as the parent class (
    "His name is:" +name);
  }
  Chinese (String Name,int age) {This
    (name);//Invokes the constructor (3) PRT that currently has the same formal parameter ("his"
    : +age);
  }
  public static void Main (string[] args) {
    Chinese cn=new Chinese ();
    Cn=new Chinese ("Kevin");
    Cn=new Chinese ("Kevin");
  }

In this program, this and super are no longer the same as they used to be. To connect a method or member, but to immediately follow the appropriate parameters, so its meaning has changed. The super parameter is used to invoke constructors in the parent class that have the same form, such as 1 and 2. This parameter then invokes the constructor that currently has the same parameters, such as 3. Of course, the various uses of this and super in the general method are still available in the overloaded constructors of Chinese, such as 4 where you can replace it with "this.prt" (because it inherits the method in the parent class) or "Super.prt." (because it is a method in the parent class and can be accessed by the Quilt Class), it can still run correctly. But this seems to be a little more than the taste of the lily.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.