一.封装的定义:
把对象的信息和内部的逻辑结构基本隐藏起来
封装的步骤
1.通过对属性的可见性的修改限制对属性的访问。
2.为每个属性创建一对赋值和取值方法
3.在赋值和取值方法中对属性的存取进行限制。
二四种访问控制符:
1、public:所修饰的类、变量、方法,在内外包均具有访问权限;
2、protected:这种权限是为继承而设计的,protected所修饰的成员,对所有子类是可访问的,但只对同包的类是可访问的,对外包的非子类是不可以访问;
3、包访问权限(default):只对同包的类具有访问的权限,外包的所有类都不能访问;
4、private:私有的权限,只对本类的方法可以使用
*用一个表格来表示
三.访问控制符使用基本原则
1.类中的绝大部分成员都应该使用Private修饰,只有一些类似全局变量的成员才考虑用public修饰。
2.如果一个类主要用做其他类的父类,该类中的方法希望被其子类重写,而不是被其他类直接调用,则应该用Protected修饰这些方法。
3.希望暴露出来给其他类自由调用的方法应该使用public修饰。
this:this代表所在函数所属对象的引用。
this的用法:当在方法内需要用到调用该方法的对象时,就用this。
下面还是附一段JAVA小白自己写的入门代码
package com.lenovo.demo;
public class Family {
private String name;
private String toothBrush;
private String cardId;
String telephone;
public String cup;
public String getName() {
return name;
}
public void setName(String name) {
if(name.length()>3) {
this.name = name;
}
}
static String house;
public String getToothBrush() {
return toothBrush;
}
public void setToothBrush(String toothBrush) {
this.toothBrush = toothBrush;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
static String tv;
public Family(String name,String toothBrush,String cardId,String telephone) {
super();
this.name = name;
this.toothBrush = toothBrush;
this.cardId = cardId;
this.telephone = telephone;
}
public void print() {
System.out.println("我是 :"+this.name+",我用的牙刷是"+this.toothBrush+",我的身份证号是"+this.cardId+",我用的手机是"+this.telephone);
}
public static void main(String[] args) {
Family child = new Family("巴巴","佳洁士","123456","vivo");
child.print();
child.setName("巴巴");
System.out.println(child.getName());
Family father = new Family("巴巴爸爸","云南白药","223456","oppo");
father.print();
Family mother = new Family("巴巴妈妈","高露洁","333456","小米");
mother.print();
}