JavaSE - class and object focus

ced485cbb11e458d81a746890b32cf3f.gif

Author: Rukawa Maple Knock Code

Blog Homepage: Rukawa Kaede's Blog

Column: Learn java with me

Quote: Stay hungry stay foolish

If you want to do good things, you must first sharpen your tools. Let me introduce you to a super powerful tool for winning offers from big manufacturers - Niuke.com

Click to register for free and brush the questions with me  

Article directory

1. Object-Oriented and Process-Oriented

2. Notes on classes

3. Class instantiation

4. this reference

5. Constructor

6. Packaging

7. Bags


1. Object-Oriented and Process-Oriented

Process-oriented: Analyzing the steps required to solve a problem, then implementing those steps with many functions

Advantages: higher performance than object-oriented , because class calls need to be instantiated, the overhead is relatively large, and resources are consumed; for example, single-chip, embedded development, Linux/Unix, etc. generally adopt process-oriented development, and performance is the most important factor.
Disadvantages: no Object-oriented, easy to maintain, easy to reuse, easy to expand

Object-oriented: Decompose the transaction that constitutes the problem into various objects. The purpose of creating an object is not to complete a step, but to describe the behavior of something in the entire problem-solving step.

Advantages: easy to maintain, reuse, and extend. Due to the characteristics of object-oriented encapsulation, inheritance, and polymorphism, a low-coupling system can be designed, making the system more flexible and easier to maintain
. Disadvantages: lower performance than process- oriented

Object-oriented is a high degree of physical abstraction, and process-oriented is top-down programming

Object-oriented is a kind of problem-solving idea, which mainly relies on the interaction between objects to complete one thing. Process-oriented is like the traditional way of washing clothes. The whole process cannot complete this problem without one link. Writing code in this way will be more troublesome to expand or maintain in the future, while object-oriented is more like modern washing. In the process of clothes, we can abstract four objects, namely: people, clothes, washing powder, and washing machines. The process of washing clothes is completed by the interaction between the four objects, and people do not need to care about the process of washing clothes.

Process-oriented and object-oriented are not a language, but a method of solving problems. There is no such thing as good or bad, and they all have their own special application scenarios.

Java is a pure object-oriented language (Object Oriented Program, inheriting OOP), in the object-oriented world, everything is an object

2. Class Notes

A class is used to describe an entity (object), mainly describing what attributes (appearance size, etc.) the entity (object) has

Class definition format:

class ClassName{
    field; //字段(属性)或者成员变量
    method; //行为或者成员方法
}

class is a keyword for defining a class, ClassName is the name of the class, and {} is the body of the class

What is contained in a class is called a member of the class

Attributes are mainly used to describe classes, called class member attributes or class member variables

The method mainly describes what functions the class has, which is called the member method of the class

Precautions:

Pay attention to the use of big camel case for class names

Before defining members, the writing method is unified as public

Usually only one class is defined in a file

The class where the main method is located generally needs to be modified with public (Note: Eclipse will find the main method in the public modified class by default)

 The class modified by public must have the same name as the file

Do not easily modify the name of the class modified by public. If you want to modify it, modify it through development tools.

3. Instantiation of the class

Recognize instantiation:

The process of creating an object with a class type is called instantiation of a class. In java, the new keyword is used, and the object is instantiated with the class name.

The new keyword is used to create an instance of an object

Use . to access properties and methods in objects

Multiple instances of the same class can be created

Class and object description:

1. A class is a model-like thing, which is used to describe an entity and defines which members of the class are

2. A class is a custom type that can be used to define variables

3. A class can instantiate multiple objects. The instantiated objects occupy the actual physical space and store class member variables.

4. Objects instantiated by a class are like building a house using architectural design drawings in reality. A class is like a design drawing. It only designs what is needed, but there is no physical building. Similarly, a class is just a design, instantiated Only the exported objects can actually store data, occupying physical space

4. this reference

this. member variable

this. access member variables

this(); access constructor

Let's see a question: 

The formal parameter name is accidentally the same as the member variable name:

public class Test {
    public int year;
    public int month;
    public int day;
    public void setDay(int year,int month,int day){
        year = year;
        month = month;
        day = day;
    }
    public void printDay(){
        System.out.println(year+"-"+month+"-"+day);
    }
    public static void main(String[] args) {
        Test test = new Test();
        test.setDay(2022,7,25);
        test.printDay();
    }
}

 The setDay method has been called in the main method and passed parameters, and printDay does not print the date. This is because the local variable takes precedence, but the formal parameter is assigned to itself, not to the member variable. At this time use this

public class Test {
    public int year;
    public int month;
    public int day;
    public void setDay(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public void printDay(){
        System.out.println(year+"-"+month+"-"+day);
    }
    public static void main(String[] args) {
        Test test = new Test();
        test.setDay(2022,7,25);
        test.printDay();
    }
}

500

 this quote:

Points to the current object (the object that calls the member method when the member method runs), and all member variable operations in the member method are accessed through this reference. It's just that all operations are transparent to the user, that is, the user does not need to pass it, and the compiler completes it automatically

Features referenced by this:

1. The type of this: the corresponding class type reference, that is, which object is called is the reference type of which object

2. this can only be used in "member methods"

3. In the "member method", this can only refer to the current object, and can no longer refer to other objects

4. this is the first hidden parameter of the "member method", and the compiler will automatically pass it. When the member method is executed, the compiler will be responsible for passing the reference of the calling member method object to the member method, and this is responsible for receiving, such as picture:

5. Constructor

When defining a local variable inside a Java method, it must be initialized, otherwise the compilation will fail

A constructor (also called a constructor) is a special member method whose name must be the same as the class name. It is automatically called by the compiler when an object is created , and is called only once in the entire object's life cycle.

Note: The function of the constructor is to initialize the members in the object, and it is not responsible for opening up space for the object

characteristic:

1. The name must be the same as the class name

2. There is no return value type, and setting it to void will not work

3. It is automatically called by the compiler when the object is created, and it is called only once in the life cycle of the object (equivalent to the birth of a person, each person can only be born once)

4. The constructor can be overloaded (users provide constructors with different parameters according to their own needs). The following two constructors have the same name and different parameter lists, so they constitute method overloading

public class Test {

    public int year;
    public int month;
    public int day;

    //无参构造方法
    public Test(){
        this.year=1900;
        this.month=1;
        this.day=1;
    }
    //带有三个参数的构造方法
    public Test(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
}

5. If the user does not explicitly define it, the compiler will generate a default constructor , and the generated default constructor must have no parameters.

public class Test {

    public int year;
    public int month;
    public int day;
    //带有三个参数的构造方法
    public Test(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public void printDate(){
        System.out.println(year+"-"+month+"-"+day);
    }

    public static void main(String[] args) {
        //报错
        Test t = new Test();
        t.printDate();
    }
}

Note: Once user defined, the compiler no longer generates

If the compiler generates it, the generated constructor is parameterless, and the object created here can also be compiled. The actual situation is an error, so once the user defines it, the compiler will no longer generate the default constructor.

 6. In the constructor, you can call other constructors through this to simplify the code

this(); access constructor

public class Test {

    public int year;
    public int month;
    public int day;

    public Test() {
        //调用本类中的其他构造方法        
        this(2022,8,4);
        System.out.println("不带参数的构造方法");
    }

    //带有三个参数的构造方法
    public Test(int year, int month, int day) {
        System.out.println("带参数的构造的方法");
        this.year = year;
        this.month = month;
        this.day = day;
    }
    
    public static void main(String[] args) {
        Test t = new Test();

    }
}

 Notice:

this(...) must be the first statement in the constructor, and an error will be reported on other lines

A ring cannot be formed, the loop call will report an error

public Date(){
    this(1900,1,1);
}
public Date(intyear,intmonth,intday){
    this();
}
/*无参构造器调用三个参数的构造器,而三个参数构造器有调用无参的构造器
形成构造器的递归调用编译报错:Error:(19,12)java: 递归构造器调用*/

7. In most cases, use public to modify, and in special cases, it will be modified by private

Note: After the code is compiled, the compiler will add all these statements for member initialization to each constructor

6. Packaging

Object-oriented programs have three major characteristics: encapsulation, inheritance, and polymorphism. The class and object phase, the main research is the encapsulation characteristics . What is encapsulation? Simply put, it is the casing shielding details.

The concept of encapsulation: organically combine data and methods of manipulating data, hide the attributes and implementation details of objects, and only expose interfaces to interact with objects

In Java, encapsulation is mainly achieved through classes and access rights : classes can combine data and methods of encapsulating data, which is more in line with human cognition of things, and access rights are used to control whether methods or fields can be used directly outside the class.

There are four access qualifiers available in Java:

No

scope private default protected public
1 same class in same package  ✔
2 Different classes in the same package
3 Subclasses in different packages
4 Non-subclasses in different packages

public (public): has the greatest access rights, and can access any class, interface, exception, etc. under the CLASSPATH. It is often used in external situations, that is, in the form of an external interface of an object or class

default (default): the default permission when nothing is written, any classes, interfaces, exceptions, etc. under this package can access each other

protected (protected): protected modifier, its main function is to protect subclasses

Private (private): access rights are limited to the inside of the class, which is a manifestation of encapsulation. For example, most member variables are decorated with private, and they do not want to be accessed by any other external classes.

After private modification name, only the same class in the same package can be called, otherwise an error will be reported

If you want to call it in other classes, you need to set the method, use the method

public class Person {
    private String name;
    public int age;
    public void setName(String name){
        this.name = name;
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("hahaha");
    }
}

Note: In general, member variables are set to private, and member methods are set to public

 get, set methods can be automatically generated by the compiler:

7. Bags

To better manage classes, multiple classes are collected together into a group called a package. Kind of like a directory. For example, in order to better manage the songs in the computer, a good way is to put the songs with the same attributes in the same file, and you can also classify the music in a certain folder in more detail.

A package is the embodiment of the encapsulation mechanism for classes, interfaces, etc. It is a good way to organize classes or interfaces. For example, classes in one package do not want to be used by classes in other packages. Packages also have an important role: classes with the same name are allowed to exist in the same project, as long as they are in different packages

 Custom package:

1. Create a new package in IDEA: Right-click src -> New -> Package

2. Enter the package name in the pop-up dialog box

3. Create a class in the package, right-click the package name -> New -> Class, and then enter the class name

4. At this point, you can see that the directory structure on our disk has been automatically created by IDEA

5. At the same time, we also see that at the top of the newly created Test.java file, a package statement appears

 common package

1. java.lang: Commonly used basic classes (String, Object) of the system, this package is automatically imported from JDK1.1

2. java.lang.reflect: java reflection programming package

3. java.net: Network programming development kit

4. java.sql: Support package for database development

5. java.util: It is a tool package (collection class, etc.) provided by java. It is very important

6. java.io: I/O programming development kit

Happy Tanabata everyone! ! And I and Xiao Wang are also happy!

 "The sharing of this issue is here, remember to give the blogger a three-link, your support is the biggest driving force for my creation!

ced485cbb11e458d81a746890b32cf3f.gif

Guess you like

Origin blog.csdn.net/chenchenchencl/article/details/126159789