class
Member variable
public class Book { private String name;//Define a String type member variable public String getName() {//Define a getName() method int id = 0;//local variable setName("Java");//Call other methods in the class return id + this.name;//Set method return value } public void setName(String name) {//Define a setNmae() method this.name = name;//Assign parameter values to member variables in the class } public Book getBook() {//Returns the Book class reference return this; } }
Member method
The syntax format for defining member methods is as follows:
Member method Permission modifier return value type method name(Parameter type parameter name){ ...//Method body return Return value; }
If a method contains a local variable with the same name as a member variable, the access to this variable in the method is carried out as a local variable.
Permission modifier
private | protected | public | |
---|---|---|---|
This category | so | so | so |
Other classes or subclasses in the same package | invisible | so | so |
Classes or subclasses of other packages | invisible | invisible | so |
When you declare a class without setting the permission of the class with a modifier, the class defaults to the package access range, that is, only a class in a package can call the member variable or member method of this class.
package com.xwk; class AnyClass { public void doString(){ ...//Method body } }
In the above code, because the modifier of the class is the default modifier, that is, only other classes and subclasses in a package can access the class, and the descring() method in AnyClass class is set to public access permission, even so, the access permission of doString() method is still the same as that of AnyClass, because the Java language stipulates that, The permission setting of class will restrict the permission setting of class members, so the above code is equivalent to the following code
package com.xwk; class AnyClass { void doString(){ ...//Method body } }
local variable
In the Book class defined above, the id variable of the getName() method is a local variable. In fact, the formal parameter in the method can also be used as a local variable. For example, when defining the setName(String name) method, the formal parameter String name is regarded as a local variable.
Local variables are created when the method is executed and destroyed at the end of the method execution. Local variables must be assigned or initialized when used, otherwise compilation errors will occur.
public String getName() {//Define a getName() method int id = 0;//local variable setName("Java");//Call other methods in the class return id + this.name;//Set method return value }
Valid range of local variables
The valid range of a local variable is from the declaration of the variable to the end of the variable.
Two local variables with the same name and type can be declared at the same time in a scope that is not nested with each other.
public void doString(String name){ int id=0; for(int i=0;i<10;i++){ System.out.print(name+String.valueOf(i)); } for(int i=0;i<3;i++){ System.out.print(i); } }
Local variables with the same name and type cannot be defined repeatedly in nested areas.
Using local variables outside the scope is a common error because there is no code that declares local variables outside the scope.
this keyword
public class Book { private String name;//Define a String type member variable public String getName() {//Define a getName() method int id = 0;//local variable setName("Java");//Call other methods in the class return id + this.name;//Set method return value } public void setName(String name) {//Define a setNmae() method this.name = name;//Assign parameter values to member variables in the class } public Book getBook() {//Returns the Book class reference return this; } }
In the above code, the name of the member variable is the same as that of the formal parameter in the setName() method. How to distinguish which variable is used in the class? In the Java language, this keyword is used to represent the reference of the object of this class. This keyword is implicitly used to reference the member variables and methods of the object. In the above code, this.name refers to the name member variable in the Book class, and the second name in this.name=name refers to the formal parameter name. The function of the setName() method is to assign the value of the formal parameter name to the member variable name.
This refers to an object of this class. When a local variable or method parameter overrides a member variable, as in the above code, add the this keyword to specify whether it refers to a class member or a local variable or method parameter.
If it is directly written as name=name, the parameter name is only assigned to the parameter variable itself. The value of the member variable name does not change because the parameter name overrides the member variable name in the scope of the method.
this can also be used as the return value of the method.
public Book getBook() {//Returns the Book class reference return this; }
In the getBook() method, the return value of the method is the Book class, and the object of the Book() class is returned in the form of return this.
Class construction method
public book(){ ...//Construction method body } public:Constructor modifier book:Name of construction method
In the construction method, you can assign values to member variables, so that when you instantiate an object of this class, the corresponding member variables will also be initialized.
If no constructor is explicitly defined in the class, the compiler automatically creates a default constructor without parameters (only if no constructor is defined in the class).
public class AnyThting { public AnyThting(){//Define parameterless construction method this("this Call parameterized constructor"); System.out.println("Nonparametric construction method"); } public AnyThting(String name){//Define parametric construction methods System.out.println("Parametric construction method"); } }
In the parameterless constructor, you can use the this keyword to call the constructor with parameters. However, this method can only be used in the first sentence of the parameterless construction method.
Static variables, constants, and methods
Variables, constants, and methods modified by the static keyword are called static variables, constants, and methods.
Static members belong to a class, which is different from individual objects. You can use the class name and "." operator to call static members in this class or other classes.
public class StaticTest { final static double PI=3.1415;//Defining static constants in a class static int id;//Defining static variables in a class public static void method1(){//Define static methods in classes //do something } public void method2(){ System.out.println(StaticTest.PI);//Call static constants System.out.println(StaticTest.id);//Call static variable StaticTest.method1();//Call static method } } //This form is generally not recommended because it is easy to confuse static members with non static members.
public class StaticTest { final static double PI=3.1415;//Defining static constants in a class static int id;//Defining static variables in a class public static void method1(){//Define static methods in classes //do something } public void method2(){ System.out.println(StaticTest.PI);//Call static constants System.out.println(StaticTest.id);//Call static variable StaticTest.method1();//Call static method } public void method3(){ method2(); return this; } }
You will find return this; An error is reported because Java has two requirements for static methods
this keyword cannot be used in static methods
Non static methods cannot be called directly in static methods
//A local variable in a method body cannot be declared static public class example{ public void method(){ static int i=0; ] }
//If you want to perform class initialization first when executing a class, you can use static to define a static area public class example{ static{ //some } }
Main method of class
public static void main(String[] args) { //Method body } //The main method is static, so if you want to call other methods directly in the main method, the method must be static. //The main method has no return value //The formal parameters of the main method are arrays. args.length can be used to get the number of parameters
public class TestMain { public static void main(String[] args) {//Define main method for(int i=0;i<args.length;i++){//Perform cyclic operation according to the number of parameters System.out.println(args[i]);//Cycle print parameter content } } }
Set in run configurations
The operation results are as follows
object
Object creation
Use the new operator to call the constructor to create the object
Test test=new Test(); Test test=new Test("a"); Test:Class name test:establish Test Class object new:Create object operator "a":Parameters of construction method
Each object is independent of each other, occupies an independent memory address in memory, and each object has its own life cycle. When the life cycle of an object ends, the object becomes garbage. It is processed by the garbage collection mechanism of the Java virtual machine and can no longer be used.
In the Java language, objects and instances can actually be common.
Let's take a look at an example of creating an object
public class CreateObject { public CreateObject(){//Construction method System.out.println("create object"); } public static void main(String[] args) {//Main method new CreateObject();//create object } } ==================== create object Process finished with exit code 0
Create an object in the main method of the above example, and the code in the construction method will be called automatically when the object is created.
Access object properties and behavior
public class TransferProperty { int i=50;//Define member variables public void call(){//Define member methods System.out.println("call call()method"); for(i=0;i<3;i++){ System.out.print(i+" "); if(i==2){ System.out.println("\n"); } } } public TransferProperty(){//Define construction method } public static void main(String[] args) { TransferProperty t1=new TransferProperty();//Create an object TransferProperty t2=new TransferProperty();//Create another object t2.i=60;//Assign the class member variable to 60 //Use the first object to call a member variable System.out.println("The first instance object calls the variable i Results:"+t1.i++); t1.call();//Calling class member methods with the first object //Use the second object to call the member variable System.out.println("The second instance object calls the variable i Results:"+t2.i); t2.call();//Use the second object to call class member methods } } ==================== The first instance object calls the variable i Results:50 call call()method 0 1 2 The second instance object calls the variable i Results:60 call call()method 0 1 2
Layout of t1 and t2 objects in memory (hand drawn)
If you want the member variable not to be changed by any of these objects, you can use the static keyword
The values of member variables declared as static can be shared by objects of this class or other classes.
public class TransferProperty { static int i=50;//Define member variables public void call(){//Define member methods System.out.println("call call()method"); for(i=0;i<3;i++){ System.out.print(i+" "); if(i==2){ System.out.println("\n"); } } } public TransferProperty(){//Define construction method } public static void main(String[] args) { TransferProperty t1=new TransferProperty();//Create an object TransferProperty t2=new TransferProperty();//Create another object t2.i=60;//Assign the class member variable to 60 //Use the first object to call a member variable System.out.println("The first instance object calls the variable i Results:"+t1.i++); t1.call();//Calling class member methods with the first object //Use the second object to call the member variable System.out.println("The second instance object calls the variable i Results:"+t2.i); t2.call();//Use the second object to call class member methods } } ==================== The first instance object calls the variable i Results:60 call call()method 0 1 2 The second instance object calls the variable i Results:3 call call()method 0 1 2
Since the t2.i=60 statement changes the value of the static member variable, the value of calling the member variable with object t1 is also 60, which is the effect of defining the i value as a static member variable. Even if two objects are used to operate on the same static member variable, the value of the static member variable can still be changed, because two objects point to the same memory area at the same time in memory.
After the t1.i + + statement is executed, the i value becomes 3. When the call() method is called again, it is re assigned to 0 for cyclic printing.
Object reference
Class name object reference name One Book()Class reference Book book; The syntax associated with a reference object is as follows: Book book=new Book();
Object comparison
public class Compare { public static void main(String[] args) { String c1=new String("abc"); String c2=new String("abc"); String c3=c1; System.out.println("c2==c3 The operation result is:"+(c2==c3)); System.out.println("c2.equals(c3)The operation result is:"+c2.equals(c3)); } }
c2==c3 The operation result is:false c2.equals(c3)The operation result is:true
==The operator compares whether the addresses referenced by two objects are equal equals()Compare whether the contents referred to by two object references are equal
Hey, this time I use Visio to draw.
Destruction of objects
Each object has a life cycle. When the life cycle of the object ends, the memory address allocated to the object needs to be recycled. In other languages, you need to recycle discarded objects manually. Java has a complete garbage collection mechanism. Users don't have to worry about the memory occupied by discarded objects. The garbage collector will automatically recycle useless resources that occupy memory.
What objects are considered "garbage" by the Java virtual machine?
Object reference exceeds its scope
..........Scope of action { Example e=new Example(); } ..........Scope of action object e Beyond its scope, it will die
Assign the object null
{ Example e=new Example(); e=null; } When the object is set to null Value, it dies.
Although the garbage collection mechanism is perfect, the garbage collector can only recycle objects created by the new operator. Some objects do not get storage space in memory through the new operator, which cannot be recognized by the garbage collection mechanism. A finalize() method is provided in Java. This method is a method of the Object class. It is declared protected. Users can define this method in their own class. If the user defines the finalize() method in the class, the method will be called first during garbage collection, and the memory occupied by the Object will not be recovered until the next garbage collection action occurs.
Garbage collection or the finalize() method is not guaranteed to happen. If the Java virtual machine runs out of memory, it will not perform garbage collection.
Since garbage collection is not controlled artificially and the specific execution time is uncertain, the finalize() method cannot be executed. To this end, Java provides a System.dc() method to force the garbage collector to start and actively inform the garbage collector to clean up.