In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 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 define and use classes and objects 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 define and use classes and objects in Java".
Classes and objects
In object-oriented, classes and objects are the most basic and important constituent units. A class is actually an abstraction that represents some basic characteristics of a certain group in an objective world. The object is to represent specific things one by one. So the class is the abstraction of the object, and the object is the concrete of the class.
"Human" is just an abstract concept, it is only a concept, is a non-existent entity! But all objects with the attributes and methods of the "human" group are called people! This object "person" is an actual entity! Everyone is an object of the "human" group.
Properties of the class
In Java, the member variables of the class define the properties of the class. The syntax for declaring member variables is as follows:
[public | protected | private] [static] [final]
The meaning of each parameter is as follows.
Public, protected, private: used to represent the access permissions of member variables.
Static: indicates that the member variable is a class variable, also known as a static variable.
Final: means that the member variable is declared as a constant and its value cannot be changed.
Type: represents the type of variable.
Variable_name: represents the variable name.
Member variables can be initialized at the same time as they are declared, and if they are not initialized when they are declared, the system initializes them with default values.
The default values for initialization are as follows:
The default value for primitive type variables of integer types (byte, short, int, and long) is 0.
The default value for the basic type variable of single-precision floating point (float) is 0.0f.
The default value for the basic type variable of double precision floating point (double) is 0.0d.
The default value for basic type variables of character type (char) is "\ u0000".
The default value for a Boolean base type variable is false.
The default value for variables of the array reference type is null. If you create an instance of an array variable but do not explicitly assign a value to each element, the element initialization value in the array takes the default value corresponding to the array data type.
Member method
Declaring member methods can define the behavior of a class, which represents what an object can do or information that can be obtained from an object. All kinds of functional operations of the class are implemented by methods, and the properties only provide the corresponding data. A complete method usually includes the method name, the method body, the method parameters, and the method return value type. If the method has a return value, use the return statement in the method body to indicate the value to be returned.
Formal parameter and actual parameter
With regard to the parameters of the method, it is often mentioned that the shape participates in the argument, which is the parameter that appears in the parameter list when the method is defined, and the argument is the parameter passed to the method when the method is called.
The formal parameters and actual parameters of the method have the following characteristics:
The parameter variable allocates memory units only when it is called, and the allocated memory units are released immediately at the end of the call. Therefore, the formal parameter is valid only within the method, and the formal parameter can no longer be used after the method call returns to the main method.
Arguments can be constants, variables, expressions, methods, and so on. No matter what type of quantity the arguments are, they must have certain values when making a method call in order to pass these values to the parameters. Therefore, we should use assignment, input and other methods to get the definite value of the actual parameter in advance.
Arguments and formal parameters should be strictly consistent in quantity, type, and order, otherwise a "type mismatch" error will occur.
The data transfer that occurs in a method call is one-way, that is, only the value of the argument can be transferred to the parameter, not the value of the parameter in the opposite direction. Therefore, during the method call, the value of the parameter changes, but the value in the argument does not change.
The data transfer of the parameter variable to the parameter variable is "value transfer", that is, it can only be passed from the parameter to the parameter, but not from the parameter to the parameter. When the member method is called in the program, Java copies the actual parameter value to a temporary storage area (stack), and any modification of the parameter is carried out in the stack. When exiting the member method, Java automatically clears the contents of the stack.
Local variable
The variables used by this method can be defined in the method body, and these variables are local variables. Its lifetime and scope are within this method, that is, local variables can only be valid or visible in this method, and these variables will be released automatically without this method.
When defining a variable in the body of a method, the variable cannot be preceded by a modifier. Local variables must be explicitly assigned before they are used, otherwise there will be errors during compilation. In addition, within a method, variables can be defined in a compound statement (a statement that encloses multiple statements in parentheses {}), and these variables are valid only in the compound statement.
Variable parameter
In the actual development process, sometimes the number of parameters in the method is uncertain. To solve this problem, the concept of variable parameters is introduced in J2SE version 5. 0.
The syntax format for declaring variable parameters is as follows:
MethodName ({paramList}, paramType... ParamName)
Where methodName represents the method name, paramList represents the fixed parameter list of the method, paramType represents the type of variable parameter, and... Is the identity that declares the variable parameter; paramName represents the name of the variable parameter.
Note: variable parameters must be defined at the end of the parameter list.
Public class StudentTestMethod {/ / define the method of outputting the number and names of students in the examination public void print (String...names) {int count = names.length; / / get the total number of System.out.println ("this time there are" + count+ "candidates, the list is as follows:"); for (int I = 0 names.length;i++ I < names.length;i++) {System.out.println (namesi]) } public static void main (String [] args) {/ / TODO Auto-generated method stub StudentTestMethod student = new StudentTestMethod (); student.print ("Zhang Qiang", "Li Cheng", "Wang Yong"); / / pass in 3 values student.print ("Ma Li", "Chen Ling");}} Construction method
A constructor is a special method of a class that initializes a new object of the class and is called automatically after the object (new operator) is created. Each class in Java has a default constructor, and can have more than one constructor.
The Java construction method has the following characteristics:
The method name must be the same as the class name
Can have 0, 1, or more parameters
There are no return values, including void
The default return type is the object type itself.
Can only be used with the new operator
It is worth noting that if you define a return value type for a constructor or use void to declare that the constructor does not return a value, there is no error at compile time, but Java treats this so-called constructor as a normal method.
At this time, you may wonder, isn't there no return value for the construction method? Why can't you declare it with void?
To put it simply, this is the grammatical rule of Java. In fact, the constructor of a class has a return value. When the constructor is called with the new keyword, the constructor returns an instance of the class, which can be treated as the return value of the constructor, so the return type of the constructor is always the current class, and there is no need to define the return type. However, you must be careful not to use return in the constructor to return the object of the current class, because the return value of the constructor is implicit.
Note: constructors cannot be modified by static, final, synchronized, abstract, and native (similar to abstract). The constructor is used to initialize a new object, so there is no point in decorating it with static. Constructors cannot be inherited by subclasses, so there is no point in decorating with final and abstract. Multiple threads do not create the same object with the same memory address at the same time, so it is not necessary to decorate it with synchronized.
Defining multiple methods of the same name with different parameters in a class is the overload of the method.
If no constructor is defined in the class, Java automatically generates a default constructor for the class. The default constructor does not contain any parameters, and the method body is empty.
The non-parameter construction method and the parameter construction method are as follows:
Public class MyClass {private int m; / / defines a private variable MyClass () {/ / defines a no-parameter constructor m = 0;} MyClass (int m) {/ / defines a parameterized constructor this.m = m;}} this keyword this. Attribute name
Most of the time, ordinary methods do not need to use the this prefix when accessing other methods and member variables, but if there is a local variable with the same name as the member variable in the method, but the program needs to access the overridden member variable in the method, it must use the this prefix.
/ / create a constructor that assigns the above three attributes the initial value public Teacher (String name,double salary,int age) {this.name = name; / / set teacher name this.salary = salary; / / set teacher salary this.age = age; / / set teacher age} this. Method name
The greatest function of the this keyword is to allow a method in a class to access another method or instance variable in that class.
Public class Dog {/ / define a jump () method public void jump () {System.out.println ("executing jump method");} / / define a run () method. The run () method requires the help of the jump () method public void run () {/ / use the this reference to call the object this.jump () of the run () method System.out.println (executing run method);}}
This () access constructor
Public class Student {String name; / / No parameter construction method (no parameter construction method) public Student () {this ("Zhang San");} / / parameter construction method public Student (String name) {this.name = name;} / / output name and age public void print () {System.out.println ("name:" + name) } public static void main (String [] args) {Student stu = new Student (); stu.print ();}}
Note:
This () cannot be used in a normal method, it can only be written in a constructor.
When used in a constructor, it must be the first statement.
Static keyword
In a class, attributes (member variables) modified with static modifiers are called static variables, or class variables, constants are called static constants, methods are called static methods or class methods, and they are collectively referred to as static members and belong to the entire class.
Static members do not depend on specific instances of the class and are shared by all instances of the class, that is, static-modified methods or variables do not need to rely on the object to access. As long as the class is loaded, the Java virtual machine can find them according to the class name.
The syntax for invoking static members is as follows:
Class name. Static member
Note:
Static-decorated member variables and methods, subordinate to the class.
Ordinary variables and methods belong to the object.
Static methods cannot call non-static members, and compilation will report an error.
Static variable
The member variables of a class can be divided into the following two categories:
Static variables (or class variables) refer to member variables modified by static.
Instance variables, which refer to member variables that are not modified by static.
The differences between static variables and instance variables are as follows:
1) static variable
At run time, the Java virtual machine allocates memory for static variables only once, and completes memory allocation for static variables during class loading.
Inside the class, static variables can be accessed directly within any method.
In other classes, static variables in the class can be accessed by the class name.
2) instance variable
Each time an instance is created, the Java virtual machine allocates memory to the instance variable.
Inside the class, instance variables can be accessed directly in non-static methods.
In static methods or other classes of this class, access is required through an instance object of the class.
The role of static variables in a class is as follows:
Static variables can be shared by all instances of the class, so static variables can be used as shared data between instances, increasing the interaction between instances.
If all instances of the class contain the same constant property, you can define this property as a static constant type, saving memory space. For example, define a static constant PI in the class.
Public class StaticVar {public static String str1 = "Hello"; public static void main (String [] args) {String str2 = "World!"; / / Direct access str1 String accessVar1 = str1+str2; System.out.println ("static variable is accessed for the first time, the result is:" + accessVar1); / / access str1 String accessVar2 = StaticVar.str1+str2 through the class name System.out.println ("the second visit to the static variable, the result is:" + accessVar2); / / access str1 StaticVar svt1 = new StaticVar () through the object svt1; svt1.str1 = svt1.str1+str2; String accessVar3 = svt1.str1; System.out.println ("the third visit to the static variable, the result is" + accessVar3) / / access str1 StaticVar svt2 = new StaticVar () through object svt2; String accessVar4 = svt2.str1+str2; System.out.println ("access static variables for the fourth time, the result is:" + accessVar4);}}
The result of running the program is as follows.
The static variable is accessed for the first time, and the result is: HelloWorld!
The static variable is accessed for the second time, and the result is: HelloWorld!
The third visit to the static variable, the result is: HelloWorld!
Visit the static variable for the fourth time, and the result is: HelloWorldwide World!
Static method
Similar to member variables, member methods can be divided into the following two types:
Static methods (or class methods) are member methods that are modified by static.
Instance method, which refers to a member method that is not modified by static.
The differences between static methods and instance methods are as follows:
Static methods can be called without any instance of the class to which they belong, so you cannot use the this keyword in static methods, nor can you directly access instance variables and instance methods of your class, but you can directly access static variables and methods of your class. In addition, like the this keyword, the super keyword is related to a specific instance of the class, so the super keyword cannot be used in static methods.
In the instance method, you can directly access the static variables, static methods, instance variables and instance methods of the class to which you belong.
Public class StaticMethod {public static int count= 1; / define static variable count public int method1 () {/ / instance method method1 count++; / / access static variable count and assign System.out.println ("count= in static method method1 ()" + count); / / print count return count } public static int method2 () {/ / static method method2 count + = count; / / access static variable count and assign System.out.println ("count= in static method method2 ()" + count); / / print count return count;} public static void PrintCount () {/ / static method PrintCount count + = 2 System.out.println ("count= in static method PrintCount () + count"); / / print count} public static void main (String [] args) {StaticMethod sft = new StaticMethod (); / / call instance method System.out.println through instance object ("method1 () method returns value intro1=" + sft.method1 ()) / / directly call the static method System.out.println ("method2 () method returns intro1=" + method2 ()); / / call the static method through the class name, print count StaticMethod.PrintCount ();}}
The result of running the program is as follows.
Count=2 in the static method method1 ()
The method1 () method returns the value intro1=2
Count=4 in the static method method2 ()
The method2 () method returns the value intro1=4
Count=6 in the static method PrintCount ()
Static code block
Refers to the static {} code block in the Java class, which is mainly used to initialize the class, assign initial values to the static variables of the class, and improve program performance.
The characteristics of static code blocks are as follows:
A static code block is similar to a method, but it cannot exist in any method body.
Static code blocks can be placed anywhere in the class, and there can be multiple static initialization blocks in the class.
The Java virtual machine executes static code blocks when classes are loaded, so most of the time, initialization operations that only need to be done once are carried out in static code blocks.
If the class contains multiple static blocks of code, the Java virtual machine executes them in the order in which they appear in the class, and each static block is executed only once.
Like static methods, static code blocks cannot directly access the instance variables and methods of the class, but need to be accessed through the instance object of the class.
Public class StaticCode {public static int count= 0; {count++; System.out.println ("non-static code block count=" + count);} static {count++; System.out.println ("static code block 1 count= + count");} static {count++; System.out.println ("static code block 2 count=" + count) } public static void main (String [] args) {System.out.println ("* StaticCode1 execution *"); StaticCode sct1 = new StaticCode (); System.out.println ("* StaticCode2 execution *") StaticCode sct2 = new StaticCode ();}}
As in the example above, in order to show that the static code block is executed only once, a non-static code block is specifically added as a comparison, and an instance object of the two classes is created in the main method. The execution result of the above example is:
Static code block 1 count=1
Static code block 2 count=2
* StaticCode1 execution *
Non-static code block count=3
* StaticCode2 execution *
Non-static code block count=4
Creation of object
An object is an instantiation of a class. An object has a state and behavior, variables are used to indicate the state of the object, and methods indicate the behavior of the object. The life cycle of Java objects includes creation, use, and cleanup. Creating objects in the Java language can be divided into explicit creation and implicit creation.
Explicitly create an object
There are four ways to create objects explicitly.
Create an object using the new keyword
This is a common way to create objects, and the syntax format is as follows:
Class name object name = new class name ()
Call the newlnstance () instance method of the java.lang.Class or java.lang.reflect.Constuctor class
In Java, you can use the newlnstance () instance method of the java.lang.Class or java.lang.reflect.Constuctor class to create an object in the following code format:
Java.lang.Class Class class object name = java.lang.Class.forName (full name of the class to be instantiated)
Class name object name = (class name) Class class object name .newInstance ()
When calling the forName () method in the java.lang.Class class, you need to pass the full name of the class to be instantiated (such as com.mxl.package.Student) as a parameter, and then call the newInstance () method of the java.lang.Class class object to create the object.
Call the object's clone () method
This method is not commonly used, and when you create an object using this method, the class to be instantiated must inherit the java.lang.Cloneable interface. The syntax format for creating an object by calling the object's clone () method is as follows:
Class name object name = (class name) created class object name.clone ()
Let's create an example to demonstrate the first three commonly used object creation methods. The sample code is as follows:
Public class Student implements Cloneable {/ / implement Cloneable interface private String Name; / / student name private int age; / / student age public Student (String name,int age) {/ / Construction method this.Name = name; this.age = age;} public Student () {this.Name = "name"; this.age = 0 } public String toString () {return "student name:" + Name+ ", age:" + age;} public static void main (String [] args) throws Exception {System.out.println ("- create an object using the new keyword -"); / / create an object Student student1 = new Student using the new keyword ("Xiao Liu", 22) System.out.println (student1); System.out.println ("- call the newInstance () method of java.lang.Class to create the object -"); / / call the newInstance () method of java.lang.Class to create the object Class C1 = Class.forName ("Student"); Student student2 = (Student) c1.newInstance () System.out.println (student2); System.out.println ("- call the object's clone () method to create the object -"); / / call the object's clone () method to create the object Student student3 = (Student) student2.clone (); System.out.println (student3);}}
The above example is explained as follows:
When you create an object using the new keyword or the newInstance () method of the Class object, the constructor of the class is called.
When you create an object using the newInstance () method of the Class class, the default constructor of the class, the no-parameter constructor, is called.
When you create an object using the clone () method of the Object class, the constructor of the class is not called, it creates a copied object that has a different memory address from the original object, but has the same property value.
If the class does not implement the Cloneable interface, clone. Method throws a java.lang.CloneNotSupportedException exception, so you should let the class implement the Cloneable interface.
The execution result of the program is as follows:
-create an object using the new keyword-
Student name: Xiao Liu, age: 22
-call the newInstance () method of java.lang.Class to create an object-
Student name: name, age: 0
-call the object's done () method to create the object-
Student name: name, age: 0
Call the readObject () of the java.io.ObjectlnputStream object
Method to implicitly create an object
In addition to explicitly creating objects, you can also create objects implicitly in Java programs, such as in the following cases.
1) String strName = "strValue", where "strValue" is a String object that is implicitly created by the Java virtual machine.
2) the result of the "+" operator operation of a string is a new String object, as shown in the following example:
String str1 = "Hello"
String str2 = "Java"
String str3 = str1+str2; / / str3 references a new String object
3) when the Java virtual machine loads a class, an Class instance describing the class is implicitly created.
Tip: class loading refers to reading the binary data from the class's .class file into memory, storing it in the method area of the runtime data area, and then creating a java.lang.Class object in the heap area to encapsulate the data structure of the class in the method area.
Summary
No matter how an object is created, the Java virtual machine includes the following steps when creating an object:
Allocate memory to the object.
Automatically initializes the instance variable of an object to the default value of its variable type.
Initialize the object and give the instance variable the correct initial value.
Note: each object is independent of each other, occupies an independent memory address in memory, and each object has its own life cycle. When an object's life cycle ends, the object becomes garbage, which is handled by the garbage collection mechanism of the Java virtual machine.
Anonymous object
Each new opens up a new object and opens up a new physical memory space. If an object needs to be used only once, anonymous objects can be used, and anonymous objects can also be passed as actual parameters.
An anonymous object is an object that is not explicitly named and is an abbreviated form of an object. Generally, anonymous objects are used only once, and anonymous objects only open up space in heap memory, and there are no references to stack memory.
Public class Person {public String name; / / name public int age; / / Age / / defines the constructor to initialize the public Person (String name, int age) {this.name = name; this.age = age;} / / method for getting information for the attribute public void tell () {System.out.println ("name:" + name + ", age:" + age)) } public static void main (String [] args) {new Person (Zhang San, 30) .tell (); / Anonymous object}}
The running result of the program is:
Name: Zhang San, age: 30
In the main method of the above program, you can find that the "new Person (" Zhang San ", 30)" statement is directly used, which is actually an anonymous object. Unlike the previously declared object, there is no stack memory reference to it, so this object is used once and is waiting to be reclaimed by GC (garbage collection mechanism).
Anonymous objects are basically passed as parameters of instantiated objects of other classes in actual development, and their usage can be found in many places in Java applications. Anonymous objects are actually heap memory space. Objects, whether anonymous or non-anonymous, can only be used after opening up the heap space.
Thank you for your reading, the above is the content of "how to define and use classes and objects in Java". After the study of this article, I believe you have a deeper understanding of how to define and use classes and objects in Java. 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.