Java object-oriented (two): class

class

Definition
of a class Write the properties and methods of the same class in the same container. This container is the class. The class is to package and manage similar properties and methods in a unified manner.

Syntax format :
[<modifier>] class <class name> { [<attribute declaration>] [<constructor declaration>] [<method declaration>] }



Note : There are only two types of modifiers, one is the default (not written), and the other is public.

Create a memory analysis of the class
Insert picture description here

Heap area:
1. All objects stored are objects, and each object contains information about a corresponding class. (The purpose of class is to get operation instructions)
2. JVM has only one heap area shared by all threads. The heap does not store basic types and object references, only the object itself.

Stack area:
1. Each thread contains a stack area, in which only the values ​​and objects of
basic data types and references to basic data are stored in the stack. 2. The data in each stack (basic data types and object references) are private, No other stacks can be accessed.
3. The stack is divided into 3 parts: basic type variable area, execution environment context, operation instruction area (store operation instructions).

Method area:
1. Also called static area, like heap, it is shared by all threads. The method area contains all the class information, constants and static variables.
2. The method area contains elements that are always unique in the entire program, such as class information, static variables

Analyze the following code memory structure

Person p1 = new Person();
P1.name = "Zhang San";
p1.age = 23;
Person p2 = new Person();
p2.name = "李四";
Person p3 = p1;

Insert picture description here

1. Attribute declaration (member variable)

Syntax format:
[<modifier>] type <attribute name> [=initial value];
Description: four modifiers can be used: public, default, protected, private

The difference between member variables and local variables

1. The defined location is different

  • Member variables: defined in the class outside the method
  • Local variables: defined in the method or as a parameter

2. The location in the memory is different

  • Member variables: objects stored in heap memory
  • Local variables: methods stored in stack memory

3. Different life cycles

  • Member variables: appear in the heap as the object appears, and disappear from the heap as the object disappears
  • Local variables: appear on the stack as the method runs, and disappear from the stack as the method ends

4. Initialization is different

  • Member variable: There is a default initial value in the heap
  • Local variable: There is no default initial value, it must be manually assigned before it can be used

5. Different access permission modifiers

  • Member variables: all 4 types of permission modifiers can be used
  • Local variables: modifiers cannot be used

Second, the definition method

Syntax format :
<modifier> <return type> <method name>([<parameter list>]) { [<statement>] }

Description:
Modifier: all four can be used.
Return value type: both basic type and reference type. No return value: void.
Method return value:

  • With return value: write the specific data type in the return value position to indicate the data type returned by the method. There must be a return statement in the method body.
  • No return value: When the method has no return value, write the void keyword and there can be no return statement. If there is a return statement, do not write any value after the return, it just means that the method ends and returns.

Three, the generation of objects

When an object is created, various types of member variables are automatically initialized and assigned. Variable types other than basic data types are reference types.
Insert picture description here
After creating a new object, we can use the format of "object name. object member" to access the members of the object.

Anonymous object

We can also directly call the method of this object without defining the handle of the object. Such objects are called anonymous objects, such as: new Person().shout(); If only one method call is required for an object, then anonymous objects can be used. We often pass anonymous objects as arguments to a function call.

Precautions for method definition and use
 a: The method cannot be defined in another method;
 b: The method name is
incorrectly
written ;  c: The parameter list is incorrectly written ;  d: The method return value is void, and the method can be Omit return and do not write, there can be no code after return;
 e: method return value type, and data type after return must match;
 f: method repeat definition problem;
 g: when the method is called, the return value is void and cannot be written In the output statement;

Fourth, the overloading of the method

 Multiple methods with the same name can be defined in the same class, that is, method overload
 The parameter list of the overloaded method must be different;
 The return value type of the overloaded method can be the same or different;
 According to the call The parameter type of the method is distinguished;

 Method overloading is irrelevant in the following situations
 Modifiers
 Return value type
 Names of formal parameters
 Method body

Five, the method of variable parameters

Java 1.5 adds a new feature:
Variable parameters: It is suitable for situations where the number of parameters is uncertain and the type is determined. Java treats variable parameters as an array.

 Note: The variable parameter must be in the last item, and a method can only have one variable parameter.

 Reason: Because the number of parameters is uncertain, when there are parameters of the same type behind it, java cannot distinguish whether the incoming parameter belongs to the previous variable parameter or the latter parameter, so the variable parameter can only be placed in the last item.

The characteristics of variable parameters:
(1) It can only appear at the end of the parameter list;
(2) ... between the variable type and the variable name, with or without spaces before and after;
(3) When calling the variable parameter method, compile The generator implicitly creates an array for the variable parameter, and accesses the variable parameter in the form of an array in the method body.

6. Method parameter value transfer mechanism (emphasis)

Method parameter value transfer mechanism:
method parameter transfer
1. Formal parameter: the parameter in the parentheses of the method when the method is declared.
Actual parameter: the value of the parameter actually passed in when the method is called

2. Rules: The parameter transfer mechanism in Java: value transfer mechanism
1) Formal parameters are of basic data type: the value of the actual parameter is passed to the variable of the basic data type of the
formal parameter 2) The formal parameter is of the reference data type: The value of the reference type variable of the actual parameter (the first address value of the object entity corresponding to the heap space) is passed to the reference type variable of the formal parameter.

Seven, common interview questions

 Define a number int[]x = new int[]{10,20,200,40,75,33,88} to remove the first element of the array from the value of each element in the array, and the result will be the position of the array On the new value, and then iterate over the new array to output.
answer:

public static void main(String[] args) {
    
    
		int[] x = new int[]{
    
    10,20,200,40,75,33,88};
		
		for (int i = x.length-1; i >= 0; i--) {
    
    
			x[i]=x[i]/x[0];
		}
		
		for(int i:x) {
    
    
			System.out.println(i);
		}

analysis:

This topic is the topic of the on-site written examination, so it is necessary to hand-write the code.
There are two pits to pay attention to here:
1. The length of the array is obtained by the attribute length, there is no () brackets, and the brackets are the length() method of the string
2. The first one needs to be removed in reverse order The number x[0], direct division in positive order, will result in x[0]=x[0]/x[0] at the beginning; the original x[0]: 10 is directly assigned to 1, and the numbers in the following array are all The division is 1, which is equal to its own value, resulting in not completing the task and losing points carelessly.
There is not only one solution to this problem, but you can also define a variable to save the value of x[0], and then divide by this variable one by one.


  • Insert picture description here
    answer:
public static void method(int a,int b) {
    
    
		
		System.out.println("a=100,b=200");
		System.exit(0);
	}
	public static void main(String[] args) {
    
    
		int a=10;
		int b=20;
		
		method(a,b);
		
		System.out.println("a="+a+",b="+b);
		
	}

Analysis:
This question is a huge pit, don’t complain, we are looking for a job, let’s recognize it, Abba Abba.
This question is actually tested on the basics. For students with weak foundations, they may skip immediately after reading the problem. Entering this big pit, remember that the transfer in java is all value transfer, there is no so-called reference transfer, not to mention the a and b here are local variables of int (basic type), and it is impossible to get the corresponding Address, it is impossible to actually change the values ​​of a and b. If you can't change it, don't change it, just output the desired result of the title, and then System.exit(0); just exit the program.
If you really encounter a problem like this in the written test (except for the online written test), if the problem is wrong, don't think about it. In this case, it is more worthwhile not to write than to write wrong. After the written test, the interview will continue. When the interviewer asked about you, you said that you thought the question was wrong, and you gave your reasons. At this time, you have already given yourself extra points for not writing this question.

 What does the following program output?
Insert picture description here
answer:

public static void main(String[] args) {
    
    
		int [] i= {
    
    2,3,4,5,6};
		
		System.out.println(i);//[I@15db9742
		
		char [] ch= {
    
    'a','b','c'};
		System.out.println(ch);//abc
		
	}

Analysis:
This topic is to investigate whether you have seen the source code of the println() method, because javinta opens a backdoor to the char[] array, which directly outputs the content to you instead of the first address.
int[] i; belongs to the reference type, and then I can directly use the source code method to see for myself why this answer is output.
It doesn't matter if the source code is not understood, remember that after the println() method is opened for char[], you can directly output the value.

//这是int[]的源码
public void println(Object x) {
    
    
        String s = String.valueOf(x);
        synchronized (this) {
    
    
            print(s);
            newLine();
        }
    }
public void print(String s) {
    
    
        if (s == null) {
    
    
            s = "null";
        }
        write(s);
    }
 private void write(String s) {
    
    
        try {
    
    
            synchronized (this) {
    
    
                ensureOpen();
                textOut.write(s);
                textOut.flushBuffer();
                charOut.flushBuffer();
                if (autoFlush && (s.indexOf('\n') >= 0))
                    out.flush();
            }
        }
        catch (InterruptedIOException x) {
    
    
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
    
    
            trouble = true;
        }
    }


//这个是char[]的源码
public void println(char x[]) {
    
    
        synchronized (this) {
    
    
            print(x);
            newLine();
        }
    }

public void print(char s[]) {
    
    
        write(s);
    }

private void write(char buf[]) {
    
    
        try {
    
    
            synchronized (this) {
    
    
                ensureOpen();
                textOut.write(buf);
                textOut.flushBuffer();
                charOut.flushBuffer();
                if (autoFlush) {
    
    
                    for (int i = 0; i < buf.length; i++)
                        if (buf[i] == '\n')
                            out.flush();
                }
            }
        }
        catch (InterruptedIOException x) {
    
    
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
    
    
            trouble = true;
        }
    }

 What does the following program output?
Insert picture description here
answer:

public void change(String s,char[]c) {
    
    
		s="test String";
		c[0]='b';
	}
	
	public static void main(String[] args) {
    
    
		Test4 test4=new Test4();
		
		String s="test";
		
		char[]c = new char[]{
    
    't','e','s','t'};
		
		test4.change(s, c);
		
		System.out.println(s);//test
		System.out.println(c);//best
		
	}

Analysis:
What is examined here is the storage characteristics of strings: once created, they cannot be modified. test4.change(s, c); The values ​​passed here are s: the address of the string "test" in the method area, c: the first address of the c array in the heap, and all the addresses are passed, but after accepting it, one At the beginning, the value of the local variable s is the address passed over, which is the address of the string "test", but when s="test String"; then the address of the local variable s changes, and the string "test Sting" is saved "The address is to directly change the address of the variable, not to change the value of the variable; the c[] array is different, the local variable c is the first address of the array, when c[0]='b' At the time, the value on the corresponding address is modified, so the original value will change accordingly.
The memory storage area is involved here. You need a certain foundation of memory storage to understand better. If you can’t understand it, then go back and make up for the knowledge of the memory structure. I talked about memory at the beginning of this article. structure.

 What does the following program output?

Insert picture description here
answer:

public static void main(String[] args) {
    
    
		String s1="你好北京";
		String s2="你好";
		
		String s3=s2+"北京";
		
		System.out.println(s1==s3);//false
		
		final String s4="你好";
		
		String s5=s4+"北京";
		
		System.out.println(s1==s5);//true
		
	}

Analysis: The code of the question and the answer are not exactly the same, but the meaning of the question has not changed in any way, so don't worry about questions with different questions and answers.
This also examines the storage characteristics of strings: the principle that they cannot be changed once they are created.
If you don’t understand, you can read this article to focus on analyzing this knowledge point.

Eight, recursive method

What is recursion? Recursion and regression, self-invoking of methods, method invoking itself,

  • So the recursive method must have an end condition, otherwise there will be an infinite loop
  • Unless necessary, it is not recommended to use recursive methods because of low efficiency

 Example: Output the Nth number of the Fibonacci sequence
 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Answer:
Insert picture description here

Concluding remarks

Continue to learn to click Object-Oriented: Package
If you don’t understand or write GTQ28 wrongly, you can leave a message~~~
bye~~~

Guess you like

Origin blog.csdn.net/zhangzhanbin/article/details/111596725