Java: packages, private (private), this keyword

Package

private (private)

Property age Student class, most people in the age range between 0 and 100, if the assignment to the age -5, is not realistic
so we want to introduce private key to hide the age,
but we define the member variables It does not make sense, so we have to provide age set and get methods for outside access
and set the age range of methods to control age

private int age;//用private修饰age,使age只能在本类中使用
//获取age的方法
public int getAge() {
    return age;
}
//设置age的方法
public void setAge(int a) {
	if(a>=0&&a<=100)	//设置判断条件,控制age的范围
    	age = a;
}

Private:
1. is a privilege modifier
2. The member variables and member methods can be modified
3. modified by its members can only be accessed in this category

Packaging: refers to the hidden object properties and implementation details, only the external provision of public access.
Package advantage: hide implementation details, provide public access, improve the reusability of code, improving safety.
Package principles: content will not be required to provide both are hidden, the hidden attribute to provide public access to its methods.
Note: private is just a reflection of the package, the package can not be equivalent to private, we first come into contact with the package is the way

this
public String name;
public void setName(String name) {
    name = name;
}
public String getName() {
    return name;
}
/*
我们说过变量的起名要做到见名知意,那么我们将setName方法中的形参名称定义为name
*/
Student s=new Student();
s.setName("xx");
System.out.println(s.getName());
/*
输出的s的name为null
当"xx"作为实参传给形参name后,执行的name=name;这个赋值语句出现了问题
我们说过,如果出现局部变量和成员变量同名情况时,方法中的局部变量会采取就近原则
即这个赋值语句中的name都是局部变量,方法没有到方法外去找成员变量name
所以成员变量name的值没有发生改变,还是null
*/
//为了避免这种现象我们要使用this关键字
public String name;
public void setName(String name) {
    this.name = name;
}
public String getName() {
    return name;
}
/*
其实getName方法中的return name;的name前也应该加上this.
*/

this represents a reference in this class, you can think that this is a representative of this class object, which object calls this method, the method of this on behalf of anyone.

Published 26 original articles · won praise 1 · views 370

Guess you like

Origin blog.csdn.net/weixin_45919908/article/details/103499872