Home  >  Article  >  Java  >  How to use access qualifiers and packages to implement encapsulation in Java?

How to use access qualifiers and packages to implement encapsulation in Java?

王林
王林forward
2023-04-23 12:52:151145browse

    1. Encapsulation

    Encapsulation is one of the three major characteristics of object-oriented programs;The three major characteristics of object-oriented programs: encapsulation, inheritance, and multiplexing state.

    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 (simply speaking, it is shell shielding detail).

    Use real objects in life to understand packaging, such as computers:

    For a complex device like a computer, all that is provided to the user is: turning on and off, inputting through the keyboard, and display , USB jack, etc., allowing users to interact with the computer and complete daily tasks.

    But in fact: the real work of the computer is the CPU, graphics card, memory and other hardware components. For computer users, they do not need to worry about the internal core components, such as how the circuits on the motherboard are laid out, how the CPU is designed, etc. Users only need to know how to turn on the computer and how to interact with the computer through the keyboard and mouse. Therefore, when computer manufacturers leave the factory, they put a shell on the outside to hide the internal implementation details, and only provide power switches, mouse and keyboard jacks so that users can interact with the computer. 2. Access qualifier (modifier)

    Encapsulation is mainly achieved through classes and access permissions in Java:

    Classes can combine data and methods of encapsulating data

    , more in line with human understanding of things, and access permissions are used to control whether a class or a method or field in a class can be used directly outside the class . Java provides four access qualifiers:

    How to use access qualifiers and packages to implement encapsulation in Java?public: public, which can be understood as a person’s appearance characteristics, anyone can see

    protected: protected, involving knowledge in inheritance, detailed introduction in the inheritance blog

    default: The default permission when writing nothing, it is not a secret for your own family (in the same package), for For others, it is privacy

    private: Private, only you know it, no one else knows

    Understand encapsulation through the code examples given below:

    class Person {
        private String name;
        //private修饰的成员变量只能在本类中访问
        private int age;
    
        String sex;
        //这里不加修饰符即为默认权限,默认是default权限
    
        public String getName() {
            return name;
        }
        //在其他类中不能直接访问name和age,
        //但可以在本类中提供公开的(public修饰)访问方法和外界进行交互
        //这里就是对成员变量进行了封装
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public void show() {
            System.out.println("姓名:"+name+" 年龄: "+age);
        }
    }
    
    public class Test {
    
        public static void main(String[] args) {
            Person person = new Person();
            //person.name = "bit";//不能直接进行访问
            person.setName("XIN-XIANG荣");
            person.setAge(21);
            //通过提供Person类中提供的方法间接进行访问
            System.out.println(person.getName()+" => "+person.getAge());
        }
    }
    Generally, member variables are set to private and member methods are set to public. Through this example, you can better understand encapsulation. Here, the implementation details inside the class are hidden/encapsulated, and only some are provided to the outside world. Public methods are accessible to other users.

    [Use scenarios of access qualifiers]:

      We hope that the class should be as "encapsulated" as possible, that is, the internal implementation details should be hidden. Only the necessary information is exposed to the caller of the class.
    • Therefore, we should use stricter access permissions as much as possible when using it; for example, if a method can be private, then Try not to use public.
    • In addition, there is a simple and crude way: set all fields as private and all methods as public. However, this method is right Abuse of access rights, but it is best to think about "who" the field methods provided by the class are used by when writing code (whether it is used by the class itself, by the caller of the class, or by subclasses)
    • 3. Package

    1. The concept of package

    In the object-oriented system, the concept of a software package is proposed, that is:

    For better management Classes collect multiple classes together into a group, called a software package

    . Somewhat similar to a directory. For example: In order to better manage pictures on your computer, a good way is to put pictures with the same attributes under the same file, or you can also classify pictures in a certain folder in more detail.

    How to use access qualifiers and packages to implement encapsulation in Java?Packages have also been introduced in Java.

    Packages are the embodiment of the encapsulation mechanism for classes, interfaces, etc., and are a good way to package classes or interfaces, etc. Organization method

    , for example: classes in one package do not want to be used by classes in other packages. Packages also play an important role: Classes with the same name are allowed to exist in the same project, as long as they are in different packages . 2. Import classes in the package

    2.1 Import method one

    Java has provided many ready-made classes for us to use. For example, Date class: you can use
    java.util.Date

    Import the Date class in the java.util package.<pre class="brush:java;">public class Test1 { public static void main(String[] args) { java.util.Date date = new java.util.Date(); // 得到一个毫秒级别的时间戳 System.out.println(date.getTime()); } }</pre>2.2 Import method two

    But this way of writing is more troublesome, you can
    use it Import statement import package

    import java.util.Date;
    public class Test1 {
        public static void main(String[] args) {
            Date date = new Date();
            // 得到一个毫秒级别的时间戳
            System.out.println(date.getTime());
        }
    }
    2.3 Import method three

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

    , You can import all classes in the java.util package here, but be careful not to import all classes at once. Whoever is used in the code will be imported. <pre class="brush:java;">import java.util.*; public class Test1 { public static void main(String[] args) { Date date = new Date(); // 得到一个毫秒级别的时间戳 System.out.println(date.getTime()); } }</pre>But

    it is more recommended to explicitly specify the class name to be imported

    . Otherwise, conflicts will still easily occur.

    import java.util.*;
    import java.sql.*;
    public class Test1 {
        public static void main(String[] args) {
    // util 和 sql 中都存在一个 Date 这样的类, 此时就会出现歧义, 编译出错
            Date date = new Date();
            System.out.println(date.getTime());
        }
    }
    
    // 编译出错
    //Error:(5, 9) java: 对Date的引用不明确
    //java.sql 中的类 java.sql.Date 和 java.util 中的类 java.util.Date 都匹配

    在这种情况下需要使用完整的类名

    import java.util.*;
    import java.sql.*;
    public class Test1 {
        public static void main(String[] args) {
            java.util.Date date = new java.util.Date();
            System.out.println(date.getTime());
        }
    }
    2.4 导入静态的方法和字段
    import static java.lang.Math.*;
    public class Test {
        public static void main(String[] args) {
            double x = 30;
            double y = 40;
    // 静态导入的方式写起来更方便一些.
    // double result = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
            double result = sqrt(pow(x, 2) + pow(y, 2));
            System.out.println(result);
        }
    }
    
    //对比正常的导入和使用
    import java.lang.Math;
    public class Test1 {
        public static void main(String[] args) {
            double x = 30;
            double y = 40;
            double result = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
            System.out.println(result);
        }
    }

    3. 自定义包

    3.1 基本使用规则:
    • 在文件的最上方加上一个 package 语句指定该代码在哪个包中.

    • 包名需要尽量指定成唯一的名字, 通常会用公司域名的颠倒形式(例如com.bat.demo1 ).

    • 包名要和代码路径相匹配. 例如创建 com.bat.demo1 的包, 那么会存在一个对应的路径 com/bat/demo1 来存储代码

    • 如果一个类没有 package 语句, 则该类被放到一个默认包中

    3.2 IDEA中创键自定义包

    在 IDEA 中先新建一个包: 右键 src -> 新建 -> 包

    How to use access qualifiers and packages to implement encapsulation in Java?

    在弹出的对话框中输入包名, 例如 com.bat.demo1 ,敲入回车即可

    How to use access qualifiers and packages to implement encapsulation in Java?

    在包中创建类, 右键包名 -> 新建 -> 类, 然后输入类名回车即可.

    How to use access qualifiers and packages to implement encapsulation in Java?

    此时可以看到我们的磁盘上的目录结构已经被 IDEA 自动创建出来了

    How to use access qualifiers and packages to implement encapsulation in Java?

    同时我们也看到了, 在新创建的 Test.java 文件的最上方, 就出现了一个 package 语句

    How to use access qualifiers and packages to implement encapsulation in Java?

    4. 不同包中的访问权限控制

    Computer类位于com.bat.demo1包中,TestComputer位置com.bat.demo2包中

    package com.bat.demo1;
    
    public class Computer {
        private String cpu; // cpu
        private String memory; // 内存
        public String screen; // 屏幕
        String brand; // 品牌
    
        public Computer(String brand, String cpu, String memory, String screen) {
            this.brand = brand;
            this.cpu = cpu;
            this.memory = memory;
            this.screen = screen;
        }
    
        public void Boot() {
            System.out.println("开机~~~");
        }
    
        public void PowerOff() {
            System.out.println("关机~~~");
        }
    
        public void SurfInternet() {
            System.out.println("上网~~~");
        }
    }

    How to use access qualifiers and packages to implement encapsulation in Java?

    注意:如果去掉Computer类之前的public修饰符,Computer类为默认权限,只能在同一包中访问,代码也会编译失败

    5. 常见的包

    • java.lang:系统常用基础类(String、Object),此包从JDK1.1后自动导入。

    • java.lang.reflect:java 反射编程包;

    • java.net:进行网络编程开发包。

    • java.sql:进行数据库开发的支持包。

    • java.util:是java提供的工具程序包;(集合类等) 非常重要

    • java.io:I/O编程开发包。

    The above is the detailed content of How to use access qualifiers and packages to implement encapsulation in Java?. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete