In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains how to use static, this, super and final in Java. The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use static, this, super and final in Java.
1. Static
Please take a look at the following program first:
Public class Hello {public static void main (String [] args) {/ / (1) System.out.println ("Hello,world!"); / / (2)}
After reading this program, it is no stranger to most people who have studied Java. Even if you have not learned Java, but have learned other high-level languages, such as C, you should be able to understand the meaning of this code. It simply outputs "Hello,world" and is of no other use. however, it shows the main use of the static keyword.
At 1, we define a static method called main, which means telling the Java compiler that I don't need to create an object of this class to use this method. Do you still have to how do you run this program? Generally, we type the following command under the command line (underlined as manual input):
Javac Hello.java
Java Hello
Hello,world!
This is the process you run. The first line is used to compile the Hello.java file. After execution, if you look at the current Hello.class file, you will find that there is one more Hello.class file, and that is the Java bytecode generated on the first line. The second line is the most common practice of executing a Java program. The result of the execution is as you expected. In 2, you might wonder why you have to do this to output. OK, let's break down this sentence. (if you do not have Java documentation installed, please visit J2SE API on Sun's official website.) first of all, System is a core class in the java.lang package. If you look at its definition, you will find this line: public static final PrintStream out; goes further, click on the hyperlink PrintStream, on the METHOD page, you will see a large number of defined methods, find println, there will be a line like this:
Public void println (String x).
Well, now you can see why we called it that way. Out is a static variable of System, so you can use it directly, and the class to which out belongs has a println method.
Static method
Typically, a method is defined as static in a class, that is, it can be called without an object of this class. As follows:
Class Simple {
Static void go () {
System.out.println ("Go...")
}
}
Public class Cal {
Public static void main (String [] args) {
Simple.go ()
}
}
Calling a static method is the class name. method name, the use of static methods is simple as shown above. In general, static methods often provide utilities for other classes in an application, and a large number of static methods in the Java class library are defined for this purpose.
Static variable
Static variables are similar to static methods. All such instances share this static variable, that is, only one piece of storage is allocated when the class is loaded, and all objects of this class can manipulate this block of storage, except for final. Look at the following code:
Class Value {static int cymbals; static void inc () {clockwise;}} class Count {public static void prt (String s) {System.out.println (s);} public static void main (String [] args) {Value v1 args v2; v1=new Value (); v2=new Value (); prt ("v1.c =" + v1.c + "v2.c =" + v2.c); v1.inc () Prt ("v1.c =" + v1.c + "v2.c =" + v2.c);}}
The results are as follows:
V1.c=0 v2.c=0
V1.c=1 v2.c=1
It can be proved that they share a storage area. Static variables are somewhat similar to the concept of global variables in C #. What is worth discussing is the initialization of static variables. Let's modify the above program:
Class Value {static int cantilever; Value () {canti15;} Value (int I) {cymbii;} static void inc () {cymbidium;}} class Count {public static void prt (String s) {System.out.println (s);} Value v=new Value (10); static Value v1 Magazine v2; static {prt ("v1.c =" + v1.c + "v2.c =" + v2.c); v1=new Value (27) Prt ("v1.c =" + v1.c + "v2.c =" + v2.c); v2=new Value (15); prt ("v1.c =" + v1.c + "v2.c =" + v2.c);} public static void main (String [] args) {Count ct=new Count (); prt ("ct.c=" + ct.v.c); prt ("v1.c =" + v1.c + "v2.c =" + v2.c); v1.inc () Prt ("v1.c =" + v1.c + "v2.c =" + v2.c); prt ("ct.c=" + ct.v.c);}}
The running results are as follows:
V1.c=0 v2.c=0v1.c=27 v2.c=27v1.c=15 v2.c=15ct.c=10v1.c=10 v2.c=10v1.c=11 v2.c=11ct.c=11
This program shows the various features of static initialization. If you come into contact with Java for the first time, the results may surprise you. You may be confused by adding parentheses after static. The first thing to tell you is that variables defined by static take precedence over any other non-static variables, regardless of the order in which they appear. As shown in the program, although v appears in front of v1 and v2, the result is that the initialization of v1 and v2 precedes v. Static {is followed by a code for explicit static variable initialization, which is initialized only once and when the class is first loaded. If you can read and understand this code, it will help you understand the static keyword. When it comes to inheritance, the static variable of the parent class is initialized first, then the subclass, and so on. Non-static variables are not the subject of this article and will not be discussed in detail here. Please refer to the explanation in Think in Java.
Static class
In general, a normal class is not allowed to be declared static, only an internal class can. At this point, the inner class, which is declared static, can be used directly as a normal class without instantiating an external class. The following code is shown:
Public class StaticCls {public static void main (String [] args) {OuterCls.InnerCls oi=new OuterCls.InnerCls ();}} class OuterCls {public static class InnerCls {InnerCls () {System.out.println ("InnerCls");}
The output will be as you expected:
InnerCls
It's the same as the ordinary class. For other uses of inner classes, see the relevant sections in Think in Java, which are not explained in detail here.
2. This & super
In the previous article, we discussed the various uses of static, which provides us with some convenience in programming by defining methods or members in static, which is similar to global functions and global variables in C to some extent. However, this is not to say that with this convenience, you can use it everywhere. In that case, you need to seriously consider whether you are programming with object-oriented ideas and whether your program is object-oriented. OK, now let's discuss the meaning and usage of the two keywords this&super.
In Java, this usually refers to the current object, and super refers to the parent class. When you want to reference something of the current object, such as a method of the current object, or a member of the current object, you can use this to do this, of course, another use of this is to call another constructor of the current object, which will be discussed in a moment. If you want to reference something from the parent class, it must be super. Since this and super have such similar features and innate relationship, we discuss them here, hoping to help you distinguish and master the two.
In the general method
The most common situation is that a parameter name in your method has the same name as a member of the current object, so in order not to be confused, you need to explicitly use the this keyword to indicate that you want to use a member, the method is "this. Member name", and the one without this is the parameter. In addition, you can use the "this. Method name" to refer to a method of the current object, but this is not necessary. You can access that method directly with the method name, and the compiler will know which one you want to call. The following code demonstrates the above usage:
Public class DemoThis {private String name; private int age; DemoThis (String name,int age) {setName (name); / / you can add this to call the method, like this: this.setName (name); but this is not a necessary setAge (age); this.print ();} public void setName (String name) {this.name=name;// you must indicate here 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); / / there is no need to use this in this line, because there is nothing that will cause confusion} public static void main (String [] args) {DemoThis dt=new DemoThis ("Kevin", "22");}}
This code is very simple and you should be able to read it without explanation. In the constructor you see that with this.print (), you can completely replace it with print (), and the effect is the same. Let's 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 (22); ds.print ();}}
In DemoSuper, the redefined print method overrides the print method of the parent class, first doing something of its own, and then calling the overridden method of the parent class. The output illustrates this:
DemoSuper:
Name=kevin Age=22
This method of use is more commonly used. In addition, if the member of the parent class can be accessed by the subclass, you can use it like this, using the "super member name of the parent class", but often you do not access the member name of the parent class in this way.
In the constructor
The constructor is a special method that is called automatically when the object is initialized. In the constructor, this and super are also used in various ways mentioned above, and there is something special about it, as shown in 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 (); / / call parent class constructor (1) prt ("A chinese."); / / (4)} Chinese (String name) {super (name) / / call constructor (2) prt ("his name is:" + name);} Chinese (String name,int age) {this (name); / / call constructor (3) prt ("his age is:" + age);} public static void main (String [] args) {Chinese cn=new Chinese (); cn=new Chinese ("kevin"); cn=new Chinese ("kevin", 22);}}
In this program, this and super no longer use "." as they used to. Join a method or member, but follow the appropriate parameters directly after it, so its meaning changes. Super is appended with parameters to call constructors of the same form in the parent class, such as 1 and 2. This is followed by a parameter to call the constructor that currently has the same parameter, such as 3. Of course, among the overloaded constructors of Chinese, various uses of this and super in general methods can still be used, such as 4, and 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 subclasses), and it still works correctly. But it seems to be a little superfluous.
Finally, having written so much, if you can keep in mind the phrase "this usually refers to the current object, and super usually refers to the parent class", then this article has achieved its goal, and you will gradually understand and master the rest in the future programming practice. Also refer to the relevant Java tutorials for the inheritance mentioned in this article.
III. Final
Final is not commonly used in Java, but it provides us with functions such as defining constants in C language. Not only that, final also allows you to control whether your members, methods, or classes can be overridden or inherited. These features make final have an indispensable position in Java, and it is also one of the keywords that you must know and master when learning Java.
Final member
When you define a variable in a class, precede it with the final keyword, that is, once the variable is initialized, it is immutable, which means that its value is immutable for the base type and its reference is immutable for the object variable. It can be initialized in two places, one at its definition, that is, directly assigning a value to the final variable when it is defined, and the other in the constructor. You can only choose one of these two places, either at the time of definition or in the constructor, not both at the time of definition and another value in the constructor at the same time. The following code demonstrates this:
Import java.util.List;import java.util.ArrayList;import java.util.LinkedList;public class Bat {final PI=3.14; / / give the address value final int i; / / when defined, because it is initialized in the constructor, so you can no longer give the value final List list; / / this variable is also the same as the above Bat () {iaddress 100; list=new LinkedList () } Bat (int ii,List l) {iambii; list=l;} public static void main (String [] args) {Bat b=new Bat (); b.list.add (new Bat ()); / / b.iroom25; / / b.list=new ArrayList (); System.out.println ("I =" + b.i+ "List Type:" + b.list.getClass ()) B=new Bat (23 ArrayList ()); b.list.add (new Bat ()); System.out.println ("I =" + b.i+ "List Type:" + b.list.getClass ());}}
This program simply demonstrates the general use of final. The method of initialization in the constructor is used here, which gives you a little flexibility. As shown in the two overloaded constructors of Bat, the first default constructor provides you with the default value, and the overloaded constructor initializes the final variable based on the value or type you provide. However, sometimes you don't need this flexibility, you just need to give its value at the time of definition and never change, so don't use this method again. There are two lines of statements in the main method that are commented out, and if you uncomment, the program cannot be compiled, that is, whether it is the value of I or the type of list, once initialized, it really cannot be changed. However, b can reinitialize to specify the value of I or the type of list, as shown in the output:
I have 100 List Type:class java.util.LinkedList
ITunes 23 List Type:class java.util.ArrayList
Another use is to define the parameter in the method as final, which does not make any practical sense for variables of the basic type, because the variable of the basic type passes the value when the method is called, that is, you can change the parameter variable in the method without affecting the calling statement, but it is useful for object variables, because object variables pass their references when they are passed. In this way, your changes to the object variables in the method will also affect the object variables in the calling statement. When you do not need to change the object variables as parameters in the method, explicitly use final to declare, which will prevent you from inadvertently modifying and affecting the calling method.
In addition, when the inner class in the method uses the parameter in the method, the parameter must also be declared as 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
By declaring a method as final, you already know that the function provided by this method meets your requirements, does not need to be extended, and does not allow any classes that inherit from this class to override the method, but inheritance can still inherit the method, that is, it can be used directly. In addition, there is a mechanism called inline, which allows 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, stacking, etc., which may improve your program efficiency, but when your method body is very large, or when you call this method in multiple places, then your calling body code will expand rapidly It may affect efficiency, so you should be careful to use final method definition.
Final class
When you use final on a class, you need to think carefully, because a final class cannot be inherited by anyone, which means that this class is a leaf class in an inheritance tree, and the design of this class is considered perfect and does not need to be modified or extended. For members in the final class, you can define them as final or not final. As for the method, it naturally becomes the final type because the class it belongs to is final. You can also explicitly add a final to a method in the final class, but this obviously doesn't make sense.
The following program demonstrates the use of the final method and the final class:
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+ "n" + str1);}} public class FinalDemo {/ / extends final cannot inherit public static void main (String [] args) {final f=new final (); f.what () F.print ();}}
As can be seen from the program, the use of the final class is almost the same as that of the ordinary class, except that it loses its inherited features. The difference between the final method and the non-final method is also difficult to see from the program line, just remember to use it with caution.
Thank you for reading, the above is the content of "how to use static, this, super and final in Java". After the study of this article, I believe you have a deeper understanding of how to use static, this, super and final in Java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.