[Java SE] Classes and Objects (Part 2)

Continue the above

Table of contents

6. Encapsulation 

6.1 Concept of encapsulation

 6.2 Access qualifiers

6.3 Package extension package

6.3.1 The concept of package

6.3.2 Custom package

6.3.3 Importing classes in packages

6.3.4 Examples of package access rights control

6.3.5 Common packages 

7. static members

7.1 static modified member variables

Edit

Edit

7.2 static modified member methods

8. Code blocks

8.1 Concept and classification of code blocks

 8.2 Common code blocks

8.3 Constructing code blocks

8.4 Static code blocks 

Summarize:  



6. Encapsulation 

6.1 Concept of encapsulation

The three major characteristics of object-oriented programs: encapsulation, inheritance, and polymorphism. In the class and object stage, the main research is on encapsulation characteristics. What is encapsulation? To put it simply, it is the shell shielding details 

class Dog {
    public String name;
    public int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void eat() {
        System.out.println(this.name + "吃东西");
    }
    public void wag() {
        System.out.println(this.name + "摇尾巴");
    }
}
public class Test {
    public static void main(String[] args) {
        Dog dog = new Dog("旺财",3);
        dog.name = "小黄";
        dog.eat();  

    }
}

These are normal writing methods and can be accessed from all places 

But in order to hide the properties and implementation details of objects, we usually hide their member variables.


 Once it is modified byprivate, other places will not be able to access its permissions, so it is protected

But it is impossible to get name directly. You can still get name

Write a construction method setName getName

You can create their names and get their names

 


 setNamegetNamealso have a quick method of construction   alt+ insert

 

Encapsulation: organically combine data and methods of operating data, hide the properties and implementation details of the object, and only expose the interface to interact with the object.


 6.2 Access qualifiers

Encapsulation is mainly achieved in Java through classes and access rights: classes can combine data and methods of encapsulating data, which is more in line with human understanding of things, while access rights are used to control whether methods or fields can be used directly outside the class. . There are four access qualifiers provided in Java:

Keyword: public is easier to understand and can be accessed anywhere

Keyword: private can only be used in the current class. After this class is released, it can no longer be used, otherwise an error will be reported.

The other two will be introduced later.


6.3 Package extension package

6.3.1 The concept of package

In the object-oriented system, the concept of a software package is proposed, that is, in order to better manage classes, multiple classes are collected together into a group, which is called a software package. somewhat similar to a directory 


For example: In order to better manage the songs on your computer, a good way is to put songs with the same attributes under the same file
, or you can also edit a folder More detailed classification of music under

Packages have also been introduced in Java.Packages are the embodiment of the encapsulation mechanism of classes, interfaces, etc., and are a good way of organizing classes or interfaces< /span>

For example: a class in one package does not want to be used by classes in other packages

Package also plays an important role:Classes with the same name are allowed to exist in the same project, as long as they are in different packages 


6.3.2 Custom package

basic rules:

  • Add a package statement at the top of the file to specify which package the code is in.
  • The package name needs to be specified as unique as possible, usually using the reverse form of the company's domain name, for example com.bit.demo1 .< /span>
  • The package name must match the code path. For example, if you create a package of com.bit.demo1, then there will be a corresponding path< /span> to store the code.com/bit/demo1
  • If a class does not have a package statement, the class is placed in a default package

1. First create a new package in IDEA: right-click src -> New -> Package

 

 

 package com.bit.demo1 is the file path

There will be no conflict between creating a Test class in com.bit.demo1 and creating a class in www

Because they are not on the same folder


 Once you have created the package, its path will be automatically generated in the file.


6.3.3 Importing classes in packages

Java has provided many ready-made classes for us to use. For example, the Date class: You can use java.util.Date to import the Date class in the java.util package.

If we feel that writing this way is too cumbersome, we can write it like this and import a package for it 

However, this way of writing is more troublesome. You can use the import statement to import the package.

 

If you need to use other classes in java.util, you can use import java.util.* 

* is a wildcard character that can display all suffixes

 

However, we recommend that you explicitly specify the class name to be imported. Otherwise, conflicts may still easily occur. 

For example, there is a class like Date in both util and sql. At this time, ambiguity will occur and compilation errors will occur.

Both places haveDatethis class,In this case you need to use the complete Class name


6.3.4 Examples of package access rights control

Here we can give an exampledefaultthis keyword

The default keyword means that it is not written by default.

 

In the same package, but different classes,default keyword can be accessed


6.3.5 Common packages 

  1.  java.lang: Commonly used basic classes (String, Object) in the system. This package is automatically imported from JDK1.1 onwards.
  2. java.lang.reflect:java reflection programming package;
  3. java.net: Development kit for network programming.
  4. java.sql: Support package for database development.
  5.  java.util: is the tool package provided by java. (Collection class, etc.) Very important
  6. java.io: I/O programming development package

7. static members

7.1 static modified member variables

Why do we need sattic variables? Let’s look at an example:

class Student {
    private String name;
    private int age;
    public String classRoom;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
public class Test {
    public static void main(String[] args) {
        Student student1 = new Student("张三",15);
        student1.classRoom = "18-101";
        Student student2 = new Student("李四",13);
        student2.classRoom = "18-101";
        Student student3 = new Student("王五",12);
        student3.classRoom = "18-101";
        System.out.println("");
    }
}

 

Three classRooms are created here, which is a bit wasteful. Obviously only one classRoom is enough.

There should be a common one, so here is onestatic keyword

Member variables modified by static are called static member variables. The biggest feature of static member variables is that they do not belong to a specific object and are shared by all objects.

 This way it only takes up one space and can be used by everyone

This recommendation can be called directly by class name.static method name (...)

 [Characteristics of static member variables]:
1. It does not belong to a specific object, but is an attribute of the class. It is shared by all objects and is not stored in the space of a certain object.
2. It can be accessed through objects or class names, but it is generally recommended to use class names to access
3. Class variables are stored in the method area
4. The life cycle follows the life of the class (that is, it is created when the class is loaded and destroyed when the class is unloaded)


7.2 static modified member methods

In Java, member methods modified by static are called static member methods. They are methods of the class and are not unique to an object. Static members are generally accessed through static methods.

[Static method characteristics]
1. It does not belong to a specific object, but is a class method
2. It can be called through an object or Called through class name.static method name (...), it is more recommended to use the latter
3. cannot be used in Access any non-static member variables in static methods


Even if this variable is not used here, an error will be reported


 There cannot be any non-static members in this static member method.

Static variables do not need to access any non-static variables

Example:

public class Test {
    public static int count = 1;
    public static void main(String[] args) {
        Test test = new Test();
        test.count++;

        Test test2 = new Test();
        test2.count++;

        Test test3 = new Test();
        test3.count++;
        
        Test.count--;

        System.out.println(Test.count);
    }
}

 

It's very simple. They all refer to the same count because it is a static variable.

Change a count;

So 3


8. Code blocks

8.1 Concept and classification of code blocks

A section of code defined using {} is called a code block. According to the position and keywords defined in the code block, it can be divided into the following four types:

  1. normal code block
  2. building blocks
  3. static block
  4. Synchronized code blocks (will be discussed later in the multi-threading section)

 8.2 Common code blocks

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

Generally used in methods 


8.3 Constructing code blocks

Construction code block: Code block defined in the class (without modifiers). Also called: instance code block. Construction code blocks are generally used to initialize instance member variables. 

class t {
    public static int staticnum = 100;
    public int date = 111;

    {
        // 一般用于初始化非静态成员变量
        System.out.println("实例代码块被执行了。。。");
        this.date = 222;
    }

}
public class Test {
    public static void main(String[] args) {
        t test1 = new t();
        System.out.println(test1.date);
    }
}


8.4 Static code blocks 

Code blocks defined using static are called static code blocks. Generally used to initialize static member variables.​ 

class t {
    public static int staticnum = 100;
    public int date = 111;

    {
        // 一般用于初始化非静态成员变量
        System.out.println("实例代码块被执行了。。。");
        this.date = 222;
    }
    static {
        System.out.println("静态代码块被执行了。。。");
        staticnum = 200;
    }

}
public class Test {
    public static void main(String[] args) {
        t test1 = new t();
        System.out.println(test1.date);
        System.out.println(t.staticnum);
    }
}

 


class t {
    public static int staticnum = 100;
    public int date = 111;

    {
        // 一般用于初始化非静态成员变量
        System.out.println("实例代码块被执行了。。。");
        this.date = 222;
    }
    static {
        System.out.println("静态代码块被执行了。。。");
        staticnum = 200;
    }
    public t() {
        System.out.println("构造方法被执行了。。。");
    }

}
public class Test {
    public static void main(String[] args) {
        t test1 = new t();
        System.out.println(test1.date);
        System.out.println(t.staticnum);
    }
}

 

 From here you can see the execution sequence:Static code block>Instance code block>Constructor method

Precautions:

  • No matter how many objects are generated, the static code block will only be executed once.
  • Static member variables are attributes of the class, so they are opened up and initialized when the JVM loads the class.
  • If a class contains multiple static code blocks, when compiling the code, the compiler will execute (merge) them in the order defined.
  • Instance code blocks are only executed when the object is created 

Summarize:  

In the future, bloggers will gradually update the knowledge of Java SE.

If there are any deficiencies, please feel free to supplement and communicate.

Friends who see this, please support the blogger and have a free three-in-one, thank you!!!

 

Guess you like

Origin blog.csdn.net/chaodddddd/article/details/134351593