Summary of Java knowledge points [3] classes and objects

1. What is process-oriented and what is object-oriented

Process-oriented: To organize the code step by step in accordance with the business process.

Object-oriented: First extract some concepts in the business as "objects", then arrange each attribute and behavior of the object, and then organize the business process.

2. What are classes and objects

The built-in types in Java are not enough, so create some types according to your actual needs, and the variables created by custom types are objects. The class is equivalent to the blueprint, and the object is the house built according to the blueprint.

3. Definition and use of classes

1) Definition example:

class Cat {
    public String name;  //姓名
    public int age;   //年龄
    public String gender;  //性别
    
    public void eat(){
        System.out.println("小猫正在吃");
    }
    public void sleep(){
        System.out.println("小猫正在睡觉");
    }

}

Class is the key to define the class, Cat is the name of the class, and {} is the main body of the class.

Among them, name, age, gender are called member attributes/member variables , and the information of these variables is the description of the class .

eat(), sleep() are called member methods , which mainly explain the functions of the class

note:

  • Use big hump for class name
  • A .java file can contain multiple classes
  • A .java file must have at least one class that is publicly modified
  • The class name modified by the public keyword must be the same as the name of the .java file (case sensitive)

2) Instantiation of the class

Instantiation is equivalent to building a house based on drawings. Use the new keyword to create an object.

Cat cat=new Cat();
cat.eat();
cat.sleep();

4. Initialization of member variables

1) Default initialization

Pay attention to distinguish what is a member variable and what is a local variable (member variables in the class, local variables in the method). If the local variable is not initialized, the compiler will report an error. If the member variables in the object are not shown to be initialized, there is a default value at this time.

rule:

  • Numeric types (including integers and floating-point numbers) are initialized to 0 by default
  • Boolean type, the default initialization is false
  • Reference type (String, array, class), the default initialization is null
  • char type, initialized to'\u000' by default

Example:

class Init{
    int a;
    long b;
    double c;
    String d;
    boolean e;

}
public class Blog{
    public static void main(String[] args) {
        Init init=new Init();
        System.out.println(init.a);
        System.out.println(init.b);
        System.out.println(init.c);
        System.out.println(init.d);
        System.out.println(init.e);
    }

}

2) In-place initialization

This is not difficult to understand, just look at the following example to understand~

class Init{
    int a=2;
    long b=20;
    double c=1.0;
    String d="";
    boolean e=true;

}

3) Initialization of the constructor

Features of the construction method :

  • The name of the constructor is the same as the class name
  • No need to write return statement
  • No need to manually display the call, but when new, it will be automatically called
  • Constructor supports overloading

Initialization using the construction method is more flexible and powerful than the previous two initialization methods :

  • The construction method can pass some parameters to dynamically obtain the value to be initialized for the object
  • The construction method can support overloading, there can be multiple construction methods, and the number or types of parameters supported by different construction methods are different. Because of this overload, you can initialize an object in different ways.

Example:

class Init{
    String name;
    public Init(String name){
        this.name=name;
    }
}
public class Blog{
    public static void main(String[] args) {
        Init init=new Init("构造方法初始化示例");
        System.out.println(init.name);
    }

}

result

Analysis: When the new object is used, the constructor is automatically called. When the parameter is passed in, the name of the formal parameter is the same as the name of the member variable name of the currently created object, so the compiler cannot distinguish the name of the formal parameter. Assigned to the formal parameter or assigned to the member variable name of the current object, so you can use the this keyword to distinguish, which means the current object , this is equivalent to "I", depending on which object the current method is called, this means who it is . So we can successfully initialize our member variable name by passing in the constructed parameters, and finally print out the results of the initialization~

Some notes about this: this can only be used in member variables. In the construction method, it must be placed in the first line, and only one .this() form can be used to call another construction method of the current class.

4) Code block initialization

This is also done by looking at the following example. It is used less, but it also has a special effect~

class Init{
    String name;
    {
        System.out.println("你好呀~我是代码块初始化时打印的哦~~");
        name="hello";
    }
}
public class Blog{
    public static void main(String[] args) {
        Init init=new Init();
        System.out.println(init.name);

    }

}

result

5) Initialization execution order of instantiated objects

Default initialization -> in-place initialization and code block initialization, whichever appears first, executes first -> constructor initialization

5.toString

There can be a toString method in any class. Through this method, an object can be converted into a String . After the conversion into a String , the String can be printed out, or saved in a file, or sent out via the network.. .

The toString method generally does not need to be called explicitly (explicit calling is also possible). When the explicit calling is not written, when the code uses this object as a string, toString will be automatically triggered (such as System. out.println())

Example:

class Init{
    int year;
    int month;
    int day;
    //构造方法
    public Init(int year,int month,int day){
        this.year=year;
        this.month=month;
        this.day=day;
    }
    //toString方法
    public String toString(){
        return this.year+"/"+this.month+"/"+this.day;
    }
}
public class Blog{
    public static void main(String[] args) {
        Init init=new Init(2020,1,20);
        System.out.println(init);

    }

}

result

6. About static

If a member is not modified by static, this is a property/member/field of an object

If a member is modified by static, this is the attribute/member/field of the class . When using it, use the method of the class name .XX . There is only one copy (it is equivalent to only one drawing, and the drawing also has its own attributes. What is the scale? It will not change the properties of the drawing due to the different objects created according to the drawing)

class Person{
    String name="一颗苹果";
    static String project="Java";
    }
public class Blog{
    public static void main(String[] args) {
        System.out.println(Person.project);
    }

}

7. Access qualifier

These qualifiers can be added before attributes or methods:

  • private: accessible inside the class
  • default: access between the same package
  • protected: not only in the same package, but also accessible by subclasses in other packages
  • public: can be accessed outside the class

Only public or nothing can be added in front of the class

What kind of access permissions should I use? It is generally hoped that the degree of code encapsulation is better, that things that can not be known from the outside should not be exposed as much as possible, and private can be used as much as possible.

8. Code block

It is a piece of code defined by {}, there are four types:

1) Common code block: the code block defined in the method

2) Building block: the code block defined in the class (without modifiers), which is generally used to initialize member variables, as mentioned above~

3) Static block: the code block defined by static is generally used to initialize static member properties

class Person{
    static String name;
    static{
        name="一颗苹果";
    }
}
public class Blog{
    public static void main(String[] args) {
        System.out.println(Person.name);
    }

}

Note: No matter how many objects are generated, a static code block will only be executed once, and it will be executed first. After the static code block is executed, the instance code block (building block) is executed, and then the constructor is executed.

The static modified code block is always executed before the ordinary code block, the static code block is executed when the class is loaded, the ordinary code block is executed when the instance is created, and the class loading is always before the instance is created (class loading only once)

4) Synchronous code block

9. Internal class

Define a class in another class or in a method, such a class is called an inner class.

1) Static inner class

static modification, indicating that it is class-related

public class Blog{

    static class B{
    }

    public static void main(String[] args) {
        B b1=new Blog.B();
        B b2=new B();//也可以省略前面的绑定
    }

}

Similar to the static method of the static variable, the static inner class is also bound to the current class (Blog), and when used, it is also called using the current class Blog.

2) Anonymous inner class (relatively more commonly used)

It is a class defined in a method or code block, and the name of the declared class is not displayed

public class Blog{
    public static void main(String[] args) {
//      定一个匿名内部类
        A a=new A(){

        };

    }
}
class A{

}

As you can see above, there is a {} after A a=new A(), indicating that the method can be rewritten. Rewriting the method in A is actually equivalent to re-creating a class (the rewritten class The function is different from the function of the previous class), but we did not give it a name, so it is called an anonymous inner class.
 

public class Test {
    public static void main(String[] args) {
        A1 a=new A1(){
           public String func(String s){
               System.out.println("hello");
               return s;
           }
        };
        System.out.println(a.func("world"));
    }
}
class A1{
    public String func(String s){
        return s;
    }
}

analysis:

In the above code, we can see that there is a class A1, which has a method func(), whose function is to print out the parameters passed in during the call. But in the main method, when we actually want to create an object based on A1, we hope that its instance can not only implement the original func() function when calling the func method, but also expect it to have other functions. As in the above example, it can also Print out "hello", so we need to rewrite the func in A1, so we add braces after A1 a=new A1(), and write the content we rewritten inside. At this time, a calls the func method The result is as follows:

It is often used when an object needs to be instantiated, but a method needs to be rewritten , such as the new interface. Abstract classes use more anonymous inner classes~~

3) Member inner class

public class Test{
    //定义一个成员内部类C
    public class C{
        
    }
    public static void main(String[] args) {
        C c=new Test().new C();
    }
}

4) Local inner class (useless)

The scope of a local inner class is similar to the scope of a local variable, defined in a method or code segment, and the scope is the same as that of an anonymous inner class.

public class Test {
    public static void main(String[] args) {
        class D extends A{
    }
    System.out.println(new D());
    }
}
class A{
}

Similar to the anonymous inner class, except that the name is displayed

10. Memory layout of classes and objects

In addition to the heap and stack, the memory area in the JVM also has a very important area, the method area. These are the further division of the memory that the JVM itself applies for from the system.

Stack: the calling relationship between methods and methods

Heap: new objects/instances

Method area: Stored one by one "class-related information" (the binary instructions of the method of each class are also here). For attributes, if the attribute is an instance attribute, it is not in the method area, but follows The instance goes (the instance is generally on the heap), if an attribute is a class attribute (static), then it is also in the method area. For methods, whether static or not, the corresponding content is in the method area.

 

Guess you like

Origin blog.csdn.net/weixin_43939602/article/details/112792844