Java package-14 days study notes

Encapsulation

  • The dew of the dew, the dew of the dew

Our program design must pursue "high cohesion, low coupling".

​ 1. High cohesion means that the internal data operation details of the class are completed by themselves, and external interference is not allowed;

​ 2. Low coupling: Only a few methods are exposed for external use. (For example, the computer only exposes some interfaces, etc., and the detailed things are encapsulated in the machine)

  • Encapsulation (hiding of data)

  • Generally, direct access-the actual representation of the data in an object should be prohibited, but should be accessed through an operating interface, which is called information hiding.

It is enough to remember this sentence: attribute private, get/set

import com.oop.Demo04.Studen;

/*
1.提高程序的安全性
2.隐藏代码的实现细节
3.统一接口
4.系统可维护增加
 */

//一个项目应该只有一个main方法
public class Application {
    
    

    public static void main(String[] args) {
    
    

         Studen x = new Studen();
         x.setName("小明");
        System.out.println(x.getName());
        x.setNumber(12);
        //快捷键 x.getNumber().sout
        System.out.println(x.getNumber());
        x.setSex('男');
        System.out.println(x.getSex());
        //不合法的
        x.setNumber(371293712);
        System.out.println(x.getNumber());
    }

}
package com.oop.Demo04;
//类
public class Studen {
    
    
    //private  属性私有,不能正常调用
    //性别
    private char sex;
    //名字
    private String name;

    //学号
    private int number;

    //学习()
    private void  study(){
    
    

    }
   //提供一些可以操作这个属性的方法。
    // 提供一些public的get/set方法
    //只有get就代表只读不写反之就是只写不读

    //get获得这个数据
    public char getSex (){
    
    
        return this.sex;
    }
    public String getName(){
    
    
        return this.name;
    }
    //set  给这个数据设置值;
    public void setName(String name){
    
    
        this.name = name;
    }
    public void setSex(char sex){
    
    
        this.sex = sex;
    } //也可以设置一样的名字重载
      public void setSex(char sex,int a){
    
    
        this.sex = sex;
    }
    //alt +回车  选getter,setter 或者两个一起
    public int getNumber() {
    
    
        return number;
    }

    public void setNumber(int number) {
    
    
        //因为封装可以做安全性的检测
        if(number > 99999 || number< 0 ){
    
    
             this.number = 0;
        }else{
    
    
            this.number = number;
        }

    }
    
}

To judge whether two classes are the same in Java, we actually mainly look at two things

//Method name parameter list method overload

Guess you like

Origin blog.csdn.net/yibai_/article/details/114809163