Detailed classes and objects in java

Process-oriented and object-oriented

  • The C language is process-oriented, focusing on the process, analyzing the steps to solve the problem, and gradually solving the problem through function calls.
  • JAVA is based on object-oriented, focusing on objects, splitting a thing into different objects, and completing it by the interaction between objects.
  • Process-oriented focuses on the process, and the behavior involved in the whole process is the function.
  • Object-oriented focuses on the object, that is, the subject involved in the process of participation. It is through logic to connect functions one by one

[Object-oriented concept]

  1. Object-oriented is a way of thinking about problems, it is a kind of thinking. For example: concepts and examples. Theory and practice. Name and reality and so on.
  2. A class is a general term for a class of objects. Object is an instance of this kind of reification
  3. The benefits of object-oriented: To make complex things simple, just face an object.

【Object Oriented Design】

Object-oriented design grasps an important experience: who owns the data, who provides external methods to manipulate the data (private)! (The passive party is the owner of the data, and the active party is the executor)

During development: find objects, build objects, use objects, and maintain relationships between objects.

Summary: Object-oriented is a way to describe things in the objective world with code (classes). A class mainly contains the attributes and behaviors of a thing

Instantiation of classes and classes

A class is a general term for a class of objects. An object is an instance of this type of reification.
A class can instantiate countless objects.

Below we use an example to understand the instantiation of classes and classes

class Person {
    
    
    public int age;//成员属性 实例变量  字段  属性
    public String name;
    public static String sex;   //静态成员变量    方法区
    public void eat() {
    
    //成员方法
        System.out.println("吃饭!");
    }
    public void sleep() {
    
    
        System.out.println("睡觉!");
    }
    public static void func(){
    
    
    	System.out.println("静态成员方法");
    }
}
public class Main{
    
    
    public static void main(String[] args) {
    
    
        Person person = new Person();//通过new实例化对象
        person.eat();//成员方法调用需要通过对象的引用调用
        person.sleep();
//产生对象 实例化对象
        Person person2 = new Person();
        Person person3 = new Person();

		//静态成员变量和方法的调用
		System.out.println(Person.sex);
		Person.func();
    }
}

Member variable:
defined inside the class, outside the method is
accessed through object references.
If not initialized, then its value is a default default value (default zero value)

  • If it is a reference type, then the value is null (including arrays, String strings, etc.)
  • If it is a simple type, then the value is the default value corresponding to its type
byte short int long float double char boolean
0 0 0 0L 0.0f 0.0 '\u0000' hexadecimal (can also be treated as 0) false

Behavior/Method:
[eat() sleep()] is an instance member method
func() is a static member method

How can I access static member variables and member methods? As
Insert picture description here
you can see here, there is no need to instantiate objects for static ones ! ! !

Direct call

Class name. Static member variable/static member method

To summarize static:

  1. For static member properties or static member methods, it does not depend on the object .
  2. There is only one static member variable, which is stored in the method area.
  3. Non-static data cannot be accessed inside a static method.

The storage structure of the instantiated class

Insert picture description here

Ways to initialize member variables

1. In-place initialization (offensive initialization within the class)
Insert picture description here

2. Default initialization
Insert picture description here
3. Out-of-class initialization (used more)

public class Main{
    
    
    public static void main(String[] args) {
    
    
        Person person1 = new Person();
        person1.name = "星星";
        person1.age = 20;

        Person person2 = new Person();
        person2.name = "狒狒";
        person2.age = 40;
    }
}

Encapsulation

When we write code, there are often two roles involved: class implementor and class caller. The essence of encapsulation is to let the caller of the class not have to understand how the implementer of the class implements the class, as long as they know how Just use the class.

This reduces the learning and use costs of class users, thereby reducing complexity

The two keywords private/ public mean "access control".

  • Member variables or member methods modified by public can be used directly by the caller of the class.
  • Member variables or member methods modified by private cannot be used by the caller of the class

for example

class Person {
    
    
    private String name = "张三";
    private int age = 18;
    public void show() {
    
    
        System.out.println("我叫" + name + ", 今年" + age + "岁");
    }
}
class Test {
    
    
    public static void main(String[] args) {
    
    
        Person person = new Person();
        person.show();
    }
}
  • At this point the field has been decorated with private. The caller of the class (in the main method) cannot use it directly. Instead, the show method is needed. At this time, the user of the class does not need to understand the implementation details of the Person class.
  • At the same time, if the implementer of the class modifies the name of the field, the caller of the class does not need to make any changes (the caller of the class does not have access to fields such as name and age at all)

getter and setter methods

Getter: the method to get the property value
setter: the method to modify the property value
We use these two methods to encapsulate the properties of the class, so as to achieve the purpose of accessing the properties

class Person {
    
    
    private String name;//实例成员变量
    private int age;
    public void setName(String name){
    
    
//name = name;//不能这样写
        this.name = name;//this引用,表示调用该方法的对象
    }
    public String getName(){
    
    
        return name;
    }
    public void show(){
    
    
        System.out.println("name: "+name+" age: "+age);
    }
}
class Main {
    
    
    public static void main(String[] args) {
    
    
        Person person = new Person();
        person.setName("caocao");
        String name = person.getName();
        System.out.println(name);
        person.show();
    }
}

this keyword

We can see the setter method in the code just now

private String name;
public void setName(String name){
    
    
		//name = name;//不能这样写
        this.name = name;//this引用,表示调用该方法的对象
}

This represents the current object reference, and you can use this to access the object's fields and methods.
Insert picture description here
Three usages:

  1. this.attribute; //Access the attributes of the current object
  2. this. method;//call the method of the current object
  3. this(); //Call the construction method of the current object (ps: must be placed in the first line, and there can only be one construction method inside)

Construction method

The construction method is a special method that will be automatically called when a new object is instantiated using the keyword new to complete the initialization operation

How many steps are there to instantiate/create an object ?
Student stu = new Student() ;//Instantiate an object in
two steps

  1. Allocate memory for the object
  2. Call the appropriate construction method, indicating that there is more than one construction method, maybe more

Grammar rules

  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 not clearly defined, the system will automatically generate a no-parameter construction)
class Person {
    
    
    private String name;//实例成员变量
    private int age;
    private String sex;
    //默认构造函数 构造对象
    public Person() {
    
    
        this.name = "caocao";
        this.age = 10;
        this.sex = "男";
    }
    //带有3个参数的构造函数
    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();//调用不带参数的构造函数 如果程序没有提供会调用不带参数的构造函数
        p1.show();
        Person p2 = new Person("zhangfei",80,"男");//调用带有3个参数的构造函数
        p2.show();
    }
}

toString method

        Person person = new Person("caocao",19);
        System.out.println(person);

If you print the reference, he will call the toString method by default, and execute such a result:
Insert picture description here
We can rewrite the toString method to print the result we want.
For example:

class Person {
    
    
    private String name;
    private int age;
    public Person(String name,int age) {
    
    
        this.age = age;
        this.name = name;
    }
    public void show() {
    
    
        System.out.println("name:"+name+" " + "age:"+age);
    }
    //重写Object的toString方法
    @Override
    public String toString() {
    
    
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Person person = new Person("caocao",19);
        person.show();
        System.out.println(person);
    }
}

Insert picture description here
In this way, the printing of the reference will be output according to the desired content.

Anonymous object

Anonymity simply means an object without a name.

  • Objects that are not referenced are called anonymous objects.
  • Anonymous objects can only be used when creating objects.
  • If an object is used only once, you don’t need to use it later, you can consider using an anonymous object
new Person("caocao",19).show();//通过匿名对象调用方法

Features: does not depend on the object, we only need to call its properties or methods through the class name

Code block

  • Native code block
  • Static code block
  • Example code block/construction code block
  • Synchronous code block (multi-threaded)

Native code block: the code block in the method

public class Main{
    
    
    public static void main(String[] args) {
    
    
        {
    
     //直接使用{}定义,普通方法块
            int x = 10 ;
            System.out.println("x1 = " +x);
        }
        int x = 100 ;
        System.out.println("x2 = " +x);
    }
}

Static code block: generally used to initialize static member properties

//静态代码块
static {
    
    
count = 10;//只能访问静态数据成员
System.out.println("I am static init()!");
}

Instance code block: the code block defined in the class, the construction code block is generally used to initialize instance member variables

//实例代码块
{
    
    
this.name = "bit";
this.age = 12;
this.sex = "man";
System.out.println("I am instance init()!");
}

Execution order

  1. Static code block
  2. Example code block
  3. Construction method

Guess you like

Origin blog.csdn.net/starry1441/article/details/113757382