面向对象-封装
一.包
本质就是文件夹 一个项目后期可能有成千上万个Java组成 为了方便后期的维护和管理,(按照功能,或者类型)分别存放在不同的包【文件夹】里面
1.定义包
1.1命名规则
一般是公司的域名反写【域名小写】
例如
www.yqhm15.cn 命名 ---------->cn.yqhem15.项目名字.模块名字
cn.yqhem15.pay 支付模块
. ----就是一个层级分割
创建包
2.导入包
概念:
就是把别人写的拿过来用 Scanner Arrays
【alt+enter 快速修复代码】
二.封装
【目的是为了安全】
权限修饰符;
1.public
2.private:被其修饰的内容只能在当前类里面使用
1.封装:
1.把类里面的成员变量【属性】使用Private修饰
2.对私有化的成员变量提供一个getter 和 setter方法,灵活的控制属性的赋值与取值
getter:【getter取值】------获取值 一般在命名上面 getXXX( ) XXX---->字段的名字
setter: void 【setter赋值】--------设置值 一般在命名上面 setXXX( ) XXX---->字段的名字
2.注意:
当属性值的类型为boolean 的时候,getXXX更改为isXXX
三.this:
1.this
1.是代表当前对象-------this就是一个对象,this所在的方法被哪个对象调用,this就是那个对象 ——this的作用就是去区分成员变量和局部变量的二义性
2.this用于在一个类里面,构造方法之间相互调用
2.注意事项:
this用于在同一个类里面,构造方法相互调用时侯,调用语句只能写在构造方法中的第一句
例如:
package com.ronghuanet._04this;
public class Student {
private String username;
private String password;
public Student(){
System.out.println("无参数的构造方法");
//this("vbaosvas");
}
public Student(String str){
//this();
System.out.println("----------------有参数构造-----------------");
}
public void setUsername(String username){
//把自己赋值给自己
//username=username;
this.username=username;
}
public void setPassword(String password){
this.password=password;
}
public String getUsername(){
return username;
}
public String getPassword(){
return password;
}
}
---------------------测试------------------------
package com.ronghuanet._04this;
public class StudentTest {
public static void main(String[] args) {
Student student = new Student();
student.setUsername("admin");
student.setPassword("123456");
System.out.println(student.getUsername());
System.out.println(student.getPassword());
Student sdas = new Student("sdas");
}
}
快捷键:【alt + insert】
例如:
package com.ronghuanet._05zj;
/*
alt+insert
*/
public class User {
private String username;
private String password;
private String nikeName;
private int age;
private boolean sex;
private String intro;
public User() {
}
public User(String username, String password, boolean sex) {
this.username = username;
this.password = password;
this.sex = sex;
}
public User(String username, String password, String nikeName, int age, boolean sex, String intro) {
this.username = username;
this.password = password;
this.nikeName = nikeName;
this.age = age;
this.sex = sex;
this.intro = intro;
}
//alt+insert ----->getter and setter
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNikeName() {
return nikeName;
}
public void setNikeName(String nikeName) {
this.nikeName = nikeName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
}