JAVA basic access control

Today we will talk about access control

What is access control?

Access control is a program outside the control class in JAVA that can access those members of the class.

Some people may ask, can the member variables of a class be accessed externally? Actually not.

This is the same as in reality. We have many attributes that cannot be disclosed to the public, such as the card number and password of your bank card, or the balance of the bank passbook, the girl’s weight, and the girl’s age are not accessible.

The same is true in JAVA, the members of our class should not be easily accessed by the outside world, or even destroyed by the outside world.
The use of class encapsulation members in JAVA is not just for the simple purpose of putting members together and storing them, but its more important purpose is to protect these members.

JAVA's 4 protection levels

The first is pubulic, public level is the most open, that is, there is no limit can easily access
the second is the private, public, and it is the opposite, it's private, that is, complete privacy, the outside world completely inaccessible
third The type is protected, which is specifically used for inheritance between parent and child classes. The
fourth type is the default control level.

Access control

Insert picture description hereBefore talking about access control, let's talk about packages first, so what is a package?

Package

・On the hard disk, a package is a folder where multiple classes (.class) are stored.
・In the program, multiple class names are organized to avoid the name space of class name conflicts.
The function of the package is to group and manage class definitions and avoid class names Conflict
・In the first line of Java source code, the package name to which the current class belongs is generally specified,
・Syntax:
・package package name; among them, all letters are recommended to be lowercase.
・Actually, the full name of a class in Java should be: package name. class name.
-For example:
Insert picture description here
・Java regulations:
-The .class file of any class must be saved in the package name folder specified in the class.
-Two classes with the same name cannot be saved in the same package

package statement

The package name can also have a hierarchical structure. Define multi-layer package name, syntax:

  • package Top-level package name. Sub-level package name...n-level package name;
    -Instructions, each level package name is connected with ".".
    -Package name hierarchy and folder hierarchy completely correspond to
    the general specification of multi-layer package names: package company or organization domain name. project name. function module name
    For example:
    org.apache.commons.lang
    org.apache company domain name
    commons project name
    lang function module

Another example: Tencent has to do a student management system. It contains a course management function module:
com.tencent .studentmgt .coursemgt

import statement

・The full name of the class must be used when accessing the class. If you do not write the full name, only the class name is used, and the default is only to search in the current package.
For example: Scanner class, in fact the full name: java.util.Scanner

java.util.Scanner sc=new java.util.Scanner(System.in);
//编译正确。但是太繁琐

The full name of the class can be introduced first through the import statement, the syntax:

  • The fully qualified name of the import class;
    -fully qualified name: is the package name. Class name

After the full name of the class is introduced through the import statement, it can be accessed using only the class name in the current source file.
For example:

import java util. Scanner;
Scanner sc=new Scanner(System.in);
//编译正确。因为已经导入了完全限定的类名

Next, we go straight to the topic to learn access control modifiers

Access control modifier

The meaning of encapsulation

Insert picture description here

The function of the fruit shop is nothing more than loading, packing, weighing, receiving payment, etc.

There are now 2 business models for fruit shops:

A: The boss acts as a shopkeeper, and the customer takes the fruit at will, weighs it at will, and asks for change at will.
B: The boss helps the client to fetch the fruit, pack it, and change it.

The first business model will definitely not work. It may open in the morning and close down in the afternoon.

The meaning of encapsulation

Provide callable and stable functions externally;
encapsulate specific internal implementation details and be inaccessible to the outside world. The advantages of this are:
-Reduce the possibility of errors and facilitate maintenance;
-Internal changes will not affect external use;


public和private

●Private modified members can only be used in member methods of this class.
●Usually class member variables should be strictly controlled using private. It can only be accessed through the methods provided by the class.
●Private modified members are for internal use only. If "public", it will greatly increase maintenance costs.
●Public modified members can be used anywhere.
●All external member methods must be very robust and stable

Classes that encapsulate the attributes and functions of the fruit shop

package day07;

/**
 * 封装水果店属性和功能的类
 */
public class Shop {
    
    
        double buying=5.5; //水果的进价5块5一斤
        double price=8; //销量8块一斤
        double total; //销售量(斤数)

        /**
         * 卖水果的方法
         * money 多少钱
         * count 多少斤
         */
         void sale(double money,double count){
    
    
            //累加销量量
            total+=count;
            //输出本次购买的结果
            System.out.println("您购买的水果"+count
                    +"斤水果,收您"+money
                    +"元,找零"+(money-price*count));
      }
}

Let’s test it first: If a customer comes to the store to buy fruit, he first looks at the purchase price and then at the selling price. He feels that the selling price is too expensive, so he changes your selling price to 0.01 yuan angrily. Give one hundred yuan.

package day07;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Shop s=new Shop();
        //加入一个顾客来买水果,先看了进价5.5元
        System.out.println(s.buying);
        //又看了看售价8元
        System.out.println(s.price);
        //他愤怒的把售价price改成为0.01
        s.price=0.01;
        //再调用sale方法
        s.sale(100,10);
    }
}

Insert picture description here
The above case shows that our purchase price cannot be easily seen or modified by people, so how to solve this problem?
Let's modify the code so that the purchase price is not visible, and the selling price cannot be modified, and private should be added!

package day07;

/**
 * 封装水果店属性和功能的类
 */
public class Shop {
    
    
       private double buying=5.5; //水果的进价5块5一斤
       private double price=8; //销量8块一斤
        double total; //销售量(斤数)

    /**
     *专门读取price属性的方法
     * 相当于老板可以告诉客人,这水果多少钱,但是客人不知道
     * @return
     */
    public double getBuying() {
    
    
        return buying;
    }
    public double getPrice() {
    
    
        return price;
    }

    /**
         * 卖水果的方法
         * money 多少钱
         * count 多少斤
         */
         void sale(double money,double count){
    
    
            //累加销量量
            total+=count;
            //输出本次购买的结果
            System.out.println("您购买的水果"+count
                    +"斤水果,收您"+money
                    +"元,找零"+(money-price*count));
      }
}

After modifying the private encryption, we can find that it cannot be read or modified, and
can only be called by the get method

package day07;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Shop s=new Shop();
        //加入一个顾客来买水果,先看了进价5.5元
        //System.out.println(s.buying);
        System.out.println(s.getBuying());

        //又看了看售价8元
        //System.out.println(s.price);
        System.out.println(s.getPrice());

        //他愤怒的把售价price改成为0.01
       // s.price=0.01; 已经无法修改
        //再调用sale方法
        s.sale(100,10);
    }
}

Insert picture description here


But the above code is still not perfect. For example, what if the user input purchase amount is less than 0? For example, what if the user amount is less than the payable amount?

Next, we continue to modify and improve this code:

package day07;

/**
 * 封装水果店属性和功能的类
 */
public class Shop {
    
    
       private double buying=5.5; //水果的进价5块5一斤
       private double price=8; //销量8块一斤
        double total; //销售量(斤数)

    /**
     *专门读取price属性的方法
     * 相当于老板可以告诉客人,这水果多少钱,但是客人不知道
     * @return
     */
    public double getBuying() {
    
    
        return buying;
    }

    public double getPrice() {
    
    
        return price;
    }

    /**
         * 卖水果的方法
         * money 多少钱
         * count 多少斤
         */
         void sale(double money,double count){
    
    
             /*公开的方法,要放出错*/
             if (money< 0 || count <=0){
    
      //数量<=0
                 System.out.println("购买的数量和钱必须>0");
             }else if (money<price*count){
    
     //钱给的不够
                 System.out.println("你的钱不够");
             }else{
    
    //正常执行逻辑
            //累加销量量
            total+=count;
            //输出本次购买的结果
            System.out.println("您购买的水果"+count
                    +"斤水果,收您"+money
                    +"元,找零"+(money-price*count));
               }
         }
}

According to the modification, we can find that the code logic is now executed normally

package day07;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Shop s=new Shop();
        //加入一个顾客来买水果,先看了进价5.5元
        //System.out.println(s.buying);
        System.out.println(s.getBuying());

        //又看了看售价8元
        //System.out.println(s.price);
        System.out.println(s.getPrice());

        //他愤怒的把售价price改成为0.01
       // s.price=0.01; 已经无法修改
        //再调用sale方法
        s.sale(50,10); //付款50元,应付款80元,钱不够
        s.sale(-10,10);//付款-10元,购买的数量和钱必须>0
    }
}

Insert picture description here

protected and default access control

●Members of default access control (do not write any modifiers) are only available in the same package
●Protected modified members can be used by classes and subclasses in the same package.

Life case: Bao is like in our reality, our community, the Shop category is like a fruit shop in our community. By default, only people in this community know about it, and people in other communities don’t.

public void sale(double money,double count){

What if we want people in other communities to know that there are fruit shops in this community? In reality, the general boss will put a big billboard at the gate of the community. Public is just equivalent to this billboard. People passing by can see it and call it.

Insert picture description here

What if we want people in other communities to know that there are fruit shops in this community? In reality, the general boss will put a big billboard at the gate of the community. Public is just equivalent to this billboard. People passing by can see it and call it.
package day07;

/**
 * 封装水果店属性和功能的类
 */
public class Shop {
    
    
       private double buying=5.5; //水果的进价5块5一斤
       private double price=8; //销量8块一斤
        double total; //销售量(斤数)

    /**
     *专门读取price属性的方法
     * 相当于老板可以告诉客人,这水果多少钱,但是客人不知道
     * @return
     */
    public double getBuying() {
    
    
        return buying;
    }

    public double getPrice() {
    
    
        return price;
    }

    /**
         * 卖水果的方法
         * money 多少钱
         * count 多少斤
         */
        public void sale(double money,double count){
    
    
             /*公开的方法,要放出错*/
             if (money< 0 || count <=0){
    
      //数量<=0
                 System.out.println("购买的数量和钱必须>0");
             }else if (money<price*count){
    
     //钱给的不够
                 System.out.println("你的钱不够");
             }else{
    
    //正常执行逻辑
            //累加销量量
            total+=count;
            //输出本次购买的结果
            System.out.println("您购买的水果"+count
                    +"斤水果,收您"+money
                    +"元,找零"+(money-price*count));
               }
         }
}

Create a new package, create a new Test

package day08;

import day07.Shop;//导入day7中的Shop类

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Shop s = new Shop();
        s.sale(100,10);
    }
}

We can find that after adding public to the method, the neighbouring community can also be purchased
Insert picture description here


At this time, we opened a branch in the neighbouring community, with the same attributes and methods as the main store.
Insert picture description here

package day07;

/**
 * 封装水果店属性和功能的类
 */
public class Shop {
    
    
       private double buying=5.5; //水果的进价5块5一斤
       private double price=8; //销量8块一斤
        double total; //销售量(斤数)

    /**
     *专门读取price属性的方法
     * 相当于老板可以告诉客人,这水果多少钱,但是客人不知道
     * @return
     */
    public double getBuying() {
    
    
        return buying;
    }

    public double getPrice() {
    
    
        return price;
    }

    /**
         * 卖水果的方法
         * money 多少钱
         * count 多少斤
         */
       protected void sale(double money,double count){
    
    
             /*公开的方法,要放出错*/
             if (money< 0 || count <=0){
    
      //数量<=0
                 System.out.println("购买的数量和钱必须>0");
             }else if (money<price*count){
    
     //钱给的不够
                 System.out.println("你的钱不够");
             }else{
    
    //正常执行逻辑
            //累加销量量
            total+=count;
            //输出本次购买的结果
            System.out.println("您购买的水果"+count
                    +"斤水果,收您"+money
                    +"元,找零"+(money-price*count));
               }
         }
}

Open a branch

package day08;

import day07.Shop;

/**
 * 开了一个分店
 */
public class SubShop extends Shop {
    
    
    /**
     * 重写父类的sale方法,使用super调用父类的sale方法
     * JAVA中规定,子类重写父类的方法,子类中的方法访问控制范围不能小于父类方法的控制范围
     */
    protected void sale(double money,double count){
    
    
        super.sale(money,count);
    }
}

test:

package day08;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        SubShop ss= new SubShop();
        ss.sale(100,10);//100块,10斤
    }
}

Insert picture description here


Access control character modifies members

The access permissions when access control characters modify members are shown in the following table:

Insert picture description here

●You can use public and default methods for class decoration. The publicly modified class can be used by any class; the class with default access control can only be used by the classes in the same package.

Guess you like

Origin blog.csdn.net/QQ1043051018/article/details/112434809