Java Se and objects

Keywords: Java Back-end JavaSE

        As we all know, C language is process oriented. It focuses on the process of the problem, analyzes the steps of solving the problem, and gradually solves the problem through function call. Java is based on object-oriented, which focuses on objects, that is, the main body involved in completing a thing, splitting a thing into different objects, and connecting the functional implementations through logic. It depends on the interaction between objects.

catalogue

1.1 object oriented concept

1.2 class and class instantiation

1.2.1 create class

1.2.2 instantiation of class

2. Members of the class

2.1 field / attribute / member variable

2.2 method

2.3 static keyword

2.3.1 accessing static member variables

2.3.2 accessing static members in static methods

2.3.2 summary memory layout:

3. Packaging

3.1 private implementation encapsulation

3.2 getter and setter methods

  4. Construction method

4.1 basic grammar

4.2 this keyword

4.2.1 this.fun( )

4.2.2 this( )

  5.1 code block

5.2 common code block

5.3 static code block

  6. Anonymous objects

  Summary:

1.1 object oriented concept

A class is a general term for a class of objects, and an object is an instance of the materialization of this class.

A complete class includes attributes and methods. Attributes are also called fields and member variables, and methods are also called member methods.

1.2 class and class instantiation

1.2.1 create class

        Class is equivalent to a template, and the object is the sample generated by the template. A class can produce countless objects. Declaring a class is to create a new data type, and the class is a reference type in Java. Java uses the keyword class to declare the class, and there can only be one class decorated with public in a. Java file.
For example:

//Class + class name. The class name is written in big hump (the first letter of each word is capitalized)
class Person{

    //Property - > also called field - > also called member variable
    //method

}

  
class Person {
    public int age;//Member property instance variable
    public String name;
    public String sex;
    public void eat() {  //Member method
    System.out.println("having dinner!");
}
  public void sleep() {
  System.out.println("sleep!");
  }
}

1.2.2 instantiation of class

(1) The process of creating objects with class types is called class instantiation
(2) A class is just a model that defines which members a class has
(3) A class can instantiate multiple objects, but the class is only a template. Only the instantiated objects occupy the actual physical space and store class member variables

In Java, we use the new keyword to create an instance of an object, and use. To access the properties and methods in the object. Multiple instances can be created in the same class.

class Person {
    public int age;//Member property instance variable
    public String name;
    public String sex;
    //Member method
    public void eat() {
        System.out.println("having dinner!");
    }
    public void sleep() {
        System.out.println("sleep!");
    }
}
public class Hang{
    public static void main(String[] args) {
        Person person = new Person();//Instantiate objects through new
        person.eat();//Member method calls need to be called by reference to the object
        person.sleep();
//A class can generate multiple objects, generate objects, and instantiate objects
        Person person2 = new Person();
        Person person3 = new Person();
    }

Note that there are three requirements when using the object (person. + field) to access the field of the object:

(1) . for various numeric types, the default value is 0
(2) . for boolean type, the default value is false
(3) . for reference types (String, Array, and custom classes), the default value is null

2. Members of the class

2.1 field / attribute / member variable

Class members include fields, methods, code blocks, internal classes, and interfaces

But let's focus on the first three

Variables usually defined in a class but outside the method. Such variables are called "field" or "attribute" or "member variables,

If we need to access the fields in the class, we need to create an object from the new instance before we can access the members inside. If multiple objects are created through the class instance, they are independent of each other. Changing the value of one object will not affect the other.

class Person {
   public String name; // field
   public int age;
}

2.2 method

Is to describe the behavior of an object

class Person {
   public int age = 18;
   public String name = "Zhang San";
   public void show() {
   System.out.println("My name is" + name + ", this year" + age + "year");
 }
}
class Test {
   public static void main(String[] args) {
   Person person = new Person();
   person.show();
 }
}

At this time, we access the method show through a new object. If we want the information of member variables, we can do the following:

Person person2 = new Person();
person2.name = "Li Si";
person2.age = 20;
person2.show()

2.3 static keyword

2.3.1 accessing static member variables

Code 1:

class Person{
    public static int count;//Static modifies a static member variable
}
public class Hang {
    public static void main(String[] args) {
    System.out.println(Person.count);//Static member variables can be accessed directly without new objects
    }

2.3.2 accessing static members in static methods

class TestDemo{
   public int a;
   public static int count;
   public static void change() {
   count = 100;//You can modify the value of a static member variable in a static method
   //a = 10; error non static data members cannot be accessed
  }
}
public class Main{
   public static void main(String[] args) {
   TestDemo.change();//Can be called without creating an instance object
   System.out.println(TestDemo.count);
  }
}

Summary: therefore, ordinary methods cannot be called inside static methods, and static variables cannot be defined inside methods.

Static member methods can be called by ordinary member methods, but on the contrary, ordinary member methods cannot be called by static member methods

Code 2:

class Person{
    public int a;
    public static int count;//The default value is 0
}
public class Hang{
    public static void main(String[] args) {
        Person t1 = new Person();
        t1.a++;//++Then 1
        Person.count++;//++Then 1
        System.out.println(t1.a);
        System.out.println(Person.count);
        System.out.println("============");
        Person t2 = new Person();
        t2.a++;
        Person.count++;//count + + and the result is 2
        System.out.println(t2.a);
        System.out.println(Person.count);
    }
}

  Next, let's look at the reasons:

The method area stores code fragments, Person.class, class,. Class, and static member variables (not objects, but classes)

  The process of running Java files:

  Next, let's review three knowledge points:

1.

Person person = null;//Indicates that this reference does not point to any object

2.

Person person = new Person;

Person person2 = person;

//Indicates that the reference of person2 points to the object pointed to by the reference of person

  3. A reference cannot point to multiple objects at the same time

4. Must the reference be on the stack?

The answer is definitely not

As shown in the figure, the reference testdemo is on the stack, the object testdemo it points to is on the heap, and the internal object person is also on the heap.

2.3.2 summary memory layout:

class Person {
        public int age;//The instance variable is stored in the object. The default value is 0
        public String name;//Instance variable. The default value is null
        public String sex;//Instance variable. The default value is 0
        public static int count;//Class variables are also called static variables. They have been generated during compilation. They belong to the class itself and have only one copy. They are stored in the method area
        public final int SIZE = 10;//A constant modified by final is also an object. It is modified by final and cannot be changed later
        public static final int COUNT = 99;//Static constants belong to the class itself. Only one is modified by final and cannot be changed later
                                           //Therefore, where an object is stored has nothing to do with whether it is modified by final
        //Instance member function
        public void eat() {
            int a = 10;//local variable
            System.out.println("eat()!");
        }
        //Instance member function
        public void sleep() {
            System.out.println("sleep()!");
        }
        //Static member function
        public static void staticTest(){
          //Non static members cannot be accessed
         //sex = "man"; error
            System.out.println("StaticTest()");
        }
    }
    public class Hang {
        public static void main(String[] args) {
            //Generate object instantiation object
            Person person = new Person();//person is a reference to the object
            System.out.println(person.age);//The default value is 0
            System.out.println(person.name);//The default value is null
            //System.out.println(person.count); / / there will be a warning!
            //Correct access method:
            System.out.println(Person.count);
            System.out.println(Person.count);
            Person.staticTest();//Summary: all methods or properties modified by static do not depend on objects
            //Accessing instance member functions
            person.eat();
            person.sleep();
        }
    }

3. Packaging

        When we write code, we often encounter two roles, namely, the implementer of the class and the caller of the class. The essence of encapsulation is to let the caller of our class not pay attention to how the class is implemented, but only know how to call the class

3.1 private implementation encapsulation

class Person {
   public String name = "Zhang San";
   public int age = 18;
}
   class Test {
   public static void main(String[] args) {
   Person person = new Person();
   System.out.println("My name is" + person.name + ", this year" + person.age + "year");
 }
}

        In this code, if the instance variable name is changed to myname one day, the amount of work we need to modify is too large. At this time, we need private to encapsulate a function. In the class call, we only need to get a free interface in the class implementation. In this way, no matter how the instance variable is changed, we only need to change it in the interface, Class directly. For example:

class Person {
   private String name = "Zhang San";
   private int age = 18;
   //Encapsulated interface
   public void show() {
   System.out.println("My name is" + name + ", this year" + age + "year");
  }
}
public class Test {
   public static void main(String[] args) {
   Person person = new Person();
   person.show();
  }
}

3.2 getter and setter methods

        We have talked about how to establish an interface to call classes more conveniently. Because functions or fields modified by private can only be called in this class, but not in other classes. Let's imagine what we should do if we want to modify the instance variables in the implementation of the class in the call of the class? Then we need to use getter (get the value of the member) and setter (set the value of the member)

Code 1:

class Person {
    private String name;//Instance member variable
    private int age;
    public void setName(String name){
    //name = name;// You can't write that
    this.name = name;//this reference represents the object that calls the method
  }
    public String getName(){
    return name;
  }
    public void show(){
    System.out.println("name: "+name+" age: "+age);
  }
}
   public static void main(String[] args) {
   
     Person person = new Person();
     person.setName("caocao");
     String name = person.getName();
     System.out.println(name);
     person.show();
}

However, if too many instance variables are modified, it is impossible to establish setter and getter methods every time, so Java has the following implementation

  4. Construction method

4.1 basic grammar

        Construction method is a special method. When a new object is instantiated with the keyword new, it will be automatically called to complete the initialization operation. We all know that calling ordinary member methods requires new an object, so what is the process?

    1. Allocate memory space for objects
    2. Call the construction method of the object

rule of grammar:

1. The method name must be the same as the class name
2. The constructor has no return value type declaration
3. There must be at least one construction method in each class (if it is not clearly defined, the system will automatically generate a parameterless construction method
 

Next, let's write a construction method:

class Person {
    private String name;//Instance member variable
    private int age;//Instance member variable
    private String sex;//Instance member variable


    public Person(){
        System.out.println("Person()::Construction method without parameters");
    }
public class Hang{
    public static void main(String[] args) {
    Person person = new person;

//The result is to print the construction method without parameters

What if we shield the constructed method without parameters:

class Person {
    private String name;//Instance member variable
    private int age;//Instance member variable
    private String sex;//Instance member variable
 }
public class Hang{
    public static void main(String[] args) {
        Person p =new Person();
}

        Therefore, even if we mask it, the result still does not report an error, because if no constructor is provided in the class, the compiler will generate a constructor without parameters by default. If a construction method is defined, the default parameterless construction will no longer be generated.

Let's write a constructor with multiple parameters:

class Person {
    private String name;//Instance member variable
    private int age;
    private String sex;
    //Default constructor construction object
    public Person() {
    this.name = "caocao";
    this.age = 10;
    this.sex = "male";
}
  //Constructor with 3 arguments
public Person(String name,int age,String sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}
  public void show(){
   System.out.println("name: "+name+" age: "+age+" sex: "+sex);
 }
}
public class Main{
  public static void main(String[] args) {
  Person p1 = new Person();//Call the constructor without parameters. If the program does not provide it, it will call the constructor without parameters
  p1.show();//Because fields are encapsulated, you can only use interfaces
  Person p2 = new Person("zhangfei",80,"male");//Call the constructor with 3 parameters
  p2.show();
 }
}

4.2 this keyword

this.data   Call the current object, i.e. property / field / member variable

this.fun( )   Call the method of the current object

this( )     Call other construction methods of the current object (stored in the constructor)

4.2.1 this.fun( )

class Person{
    private String name;
    public void eat(){
        System.out.println(name+"I am eating");
    }
    public  void print(){
        this.eat();//Call the eat method of the current object, but this cannot be used in static methods, otherwise an error will be reported
        System.out.println("full name:"+name);
    }
}

4.2.2 this( )

class Person{
    private String name;

    public Person(){
        this("Zhang San");//You cannot use this() before you construct an object
        System.out.println("Construction method without parameters");
    }
    public Person(String name){
        System.out.println("Construction method with one parameter");
    }
}
public class Hang{
    public static void main(String[] args) {
        Person person = new Person();//At this moment, call the parameterless constructor through the new object, and execute the first language first 
                                     //Sentence, this("Zhang San"), call again now
                                     //Call the constructor with one parameter, and then call the constructor without parameters 
                                     //Constructor, but at this point this() must be placed in the first sentence   
    }
}

  5.1 code block

A piece of code defined with {} is a code block

It can also be divided into four types: local code blocks

                          Tectonic block

                          Static block

                          Synchronous code block

But let's start with ordinary code blocks and static blocks

5.2 common code block

class Person{

   private String name;
   {
      System.out.println("Instance code block");
   }
  
   static{
      System.out.println("Static code block")

    }

As a result, static code blocks are output first, and then instance code blocks are output.

5.3 static code block

Code block defined using static. Generally used to initialize static member properties
 

class Person{
    private String name;
    public static int count = 4;
    {
        this.name="Zhang San";
        System.out.println("Instance code block");
    }
    static {
        count = 8;//this cannot be used for static code blocks decorated with static because it belongs to a class and not an object
        System.out.println("Static code block");
    }
}
public class Hang{
    public static void main(String[] args) {
        System.out.println(Person.count);
    }
}

  Static code blocks can be executed without instantiation

There are two other situations that can reflect the execution process of static code blocks:

Code 1:

class Person{
    private String name;
    static {
        count=8;
        System.out.println("Static code block");
    }
    public static int count =10;//If count has been assigned at this time, the runtime follows the static variable
}
public  class Hang{
    public static void main(String[] args) {
        System.out.println(Person.count);
    }
}

  Code 2:

class Person{
    private String name;
    static {
        count=8;
        System.out.println("Static code block");
    }
    public static int count ;//If count is not assigned at this time, run the code and count takes the count in the static method
}
public  class Hang{
    public static void main(String[] args) {
        System.out.println(Person.count);
        Person p1 = new Person();
        Person p2 = new Person();
    }
}
//No matter how many objects are generated, the static code block will be executed only once and first, so p2 will not run

  6. Anonymous objects

(1) Anonymity simply means an object without a name
(2) Objects that are not referenced are called anonymous objects
(3) Anonymous objects can only be used when creating objects
(4) If an object is used only once and does not need to be used later, consider using anonymous objects

  Summary:

        A class can produce countless objects. A class is a template and an object is a concrete instance.
The attributes defined in class can be roughly divided into several categories: class attributes and object attributes. The data attributes modified by static are called   class   Attribute, the method modified by static is called class method, which is characterized by not depending on the object. We can call its attribute or method only through the class name. Static code block takes precedence over instance code block, and instance code block takes precedence over constructor.
The this keyword represents a reference to the current object. It is not the current object.

Posted by Jessup on Fri, 05 Nov 2021 14:39:08 -0700