Home  >  Article  >  Java  >  What does private mean in java

What does private mean in java

(*-*)浩
(*-*)浩Original
2019-05-22 11:50:5552377browse

Private as a permission modifier can modify classes, properties and methods; classes, properties and methods modified with private can only be used by yourself and cannot be accessed by other classes, that is to say, for other classes It is hidden and invisible. Private generally does not modify classes, but it can modify internal classes.

What does private mean in java

You can use private to implement encapsulation:

Encapsulate properties and methods with private to represent the encapsulated properties and methods can only be used within this class and are not visible outside the class.

If you want to access the encapsulated properties at this time, you must provide getter and setter methods

setter method: mainly for setting and modifying the attribute content

getter method: mainly for setting and modifying the attribute content Obtaining attribute content

Design principles for classes: When writing a class, there is no additional explanation. All attributes must be encapsulated privately (member variables)

private cannot be used for external classes Encapsulation, but can be used for encapsulation of inner classes:

class Persion{
    //被private封装的属性
    private String name;
    private int age;
    public void setname(String n){
        name = n;
    }
    public String getname(){
        return name;
    }
    public void setage(int num){
        if(num>0 && num<150){
            age = num;
        }
        else{
            age = 0;
        }
    }
    public int getage(){
        return age;
    }
    public void getPersionInfo(){
        System.out.println("姓名:"+name+", 年龄:"+age);
    }
}
public class test{
    public static void main(String[] args){
        Persion per1 = new Persion();
        per1.setname("guo");//通过set方法设置参数
        per1.setage(200);
        per1.getPersionInfo();//获取参数
    }
}

private is only the first step in encapsulation.

Related learning recommendations: java basic tutorial

The above is the detailed content of What does private mean in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn