Classes and objects

I believe that there should be many people like me who started with the C language when they studied in school, and then started to learn Java. The C language is actually quite different from Java:

C language is a process-oriented , and concerned that the process of analyzing the steps to solve problems, to solve the problem step by step through the function call.
JAVA is based on object-oriented and concerned with the object , the thing split into different objects, by interactions between objects is completed.

Process-oriented focus is a process , the behavior of the whole process involved is functional .
Object-oriented focus is the object , which is involved in the processes involved in the body . It is to connect each function realization through logic.

Process-oriented: 1. Open the refrigerator 2. Put the elephant in 3.
Close the refrigerator Object-oriented: Open the refrigerator, store, and close the refrigerator. It is the behavior of the refrigerator. The refrigerator is an object, so as long as the function of the refrigerator is operated, it must be defined in the refrigerator.

So what exactly are classes and objects ?
Class : It is the collective name of a class of objects.
Object : It is an instance of this kind of concretization. The object is the abstraction and modeling of things in reality.

Take a chestnut: The mold we make moon cakes is a class, and moon cakes can be made through this mold. Then in this example, the class is the mold and the moon cake is the object, so the moon cake is an entity. A model can instantiate countless objects.
A class is equivalent to a template, and an object is a sample generated by the template. A class can produce countless objects.

To declare a class is to create a new data type. The class is a reference type in Java:
1. The members of the class can include: fields (attributes, member variables), methods, code blocks, internal classes and interfaces, etc.
2. If an object Create out attribute is not initialized, will be provided a default initial value:
for basic data types , the default value is 0 , Boolean type of exception, the default value to false ; for reference types (String, array, and a custom class ), the default value is null (null reference)

//创建一个类
//class为定义类的关键字,Person为类名
class Person {
    
      
    public int age;//成员属性 实例变量
    public String name;
    public void eat() {
    
    //成员方法
       System.out.println("吃饭!");  
   }
    public void sleep() {
    
    
       System.out.println("睡觉!");  
   }
}

public class Main{
    
    
 public static void main(String[] args) {
    
    
    //产生对象     实例化对象
        Person person = new Person(); //通过 new 实例化对象
        person.age = 20;
        person.name = "qbs";
        person.eat(); //成员方法调用需要通过对象的引用调用
        person.sleep();
       
 }
}

Guess you like

Origin blog.csdn.net/qq_45658339/article/details/108907776