Dabai became the eighteenth day of Java software siege lion (object-oriented encapsulation, static)

Object-oriented encapsulation

Benefits of encapsulation:

  • 1. After encapsulation, for that thing, you can't see the more complicated side of the thing, only the simple side of the thing. Complexity encapsulation provides simple operation entrance to the outside . The camera is a good case. The realization principle of the camera is more complicated, but it is very convenient for the people who use the camera. Also, like TV sets are also packaged, the TV memory implementation is very complicated, but users do not need to care about the internal implementation principles, only need to operate the remote control.
  • 2. After encapsulation, a real "object" and a real " independent body " will be formed .
  • 3. Encapsulation means that future programs can be reused. And this thing should be more adaptable and can be used in any situation. Reusability
  • 4. After encapsulation, the security of the thing itself is improved [ high security level ]

Encapsulation steps:

1. All attributes are privatized, and the private keyword is used for modification. Private means private, and all modified data can only be accessed in this class

2. Provide simple operation entrances to the outside, that is to say, if external programs want to access the age attribute, they must access them through these simple entrances:

  • Provide two public methods, namely set method and get method
  • To modify the age attribute, call the set method
  • To read the age attribute, call the get method

3. Naming convention of set method:public void set + 属性名首字母大写(形参){ };

public  void setAge(int a){
    
     
	age = a; 
}

4. The naming convention of get method:public 返回值类型 get + 属性名首字母大写(形参){ };

public int getAge(){
    
    
	return age;
}

5. Need to remember:

  • The setter and getter methods have no static keyword
  • How to call a method modified with static keyword?类名.方法名(实参);
  • How to call a method without static keyword modification?引用.方法名(实参);

Example:

public class UserTest
{
    
    
	public static void main(String[] args){
    
    
		User user =new User();
		//编译报错,age属性私有化,在外部程序中不能直接访问
		//从此之后age属性非常的安全,但是有点太安全了。
		//对于目前程序来说,age属性彻底在外部访问不到了。
		//System.out.println(user.age);
       
       //修改
       user.setAge(-100);//对不起,您提供的年龄不合法
       //读取
       System.out.println(user.getAge());//0
	}
}
public class User
{
    
    
	//属性私有化
	private int age;
}

public  void setAge(int a){
    
     
	//编写业务逻辑代码进行安全控制
	//age = a; 
	
	if(a<0||a>150){
    
    
		System.out.println("对不起,您提供的年龄不合法");
		return;
	}
	//程序可以进行到这里的话,说明a是合法的,则进行赋值运算
	age = a; 
}

public  int getAge(){
    
    
	return age;
}

Guess you like

Origin blog.csdn.net/qq2632246528/article/details/113062563