private - 修饰符
含义:私有化,只能在类里面调用
作用:
1.修饰属性:私有化属性,不让外界调用。
2.修饰方法:私有化方法, 不让外界调用
用private修饰后的方法和属性不能被外界直接调用,防止属性在外界直接被修改,起保护作用。
public class Wallet{
private String name;
private int money1;
int money2;
public void setmoney1(money){
money1=money;//私有变量在Wallet类里是可以调用的
}
public void getmoney1(){
System.out.println(name+"余额还有"+money1);
}
}
public class Test{
public static void main(){
Wallet wallet = new Wallet();
wallet.money2=100;
//wallet.money1=100;//这里会报错,因为money1已经被私有化了,在外面是无法被调用的
wallet.setmoney1(100);
System.out.println(wallet.money2);
wallet.getmoney1();
}
}
this
this - 本对象
含义:代表本对象,this出现方法里,表示调用该方法所在的对象
this.变量名:表示调用方法所在类的变量
this.方法名:表示调用方法所在类的其他方法或者本方法(方法名是谁就调用谁)
this():表示调用本类的构造方法
封装
步骤:
1.先私有化属性
2.添加get方法和set方法:get方法用于获取数据,set方法用于设置数据
优点:
1.保护属性安全,使属性不会被外界直接调用
2.添加get/set方法后,可以在获取方法(get())和设置方法(set())中做额外的功能。
实例:模拟银行用户类
public class User {
private String account;//账户
private String name;//姓名
private String password;//密码
private double balance;//余额
//无参构造
public User() {
}
//有参构造
public User(String account, String name, String password, double balance) {
super();
this.account = account;
this.name = name;
this.password = password;
this.balance = balance;
}
//获取余额
public double getBalance() {
return balance;
}
//设置金额
public void setBalance(double balance) {
this.balance = balance;
}
}
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
User user = new User("1750159674","Xuwenxing", "123123", 10000);
System.out.println("输入取款金额");
double money = scanner.nextInt();
System.out.println("余额为"+user.getBalance());//获取余额
System.out.println("取款"+money);
user.setBalance(user.getBalance()-money);//取两百块钱
System.out.println("余额为"+user.getBalance());//获取余额
}
}
总结:编写类的流程
1.属性
2.私有化属性
3.无参、有参构造
4.get/set方法
分包
作用:
1.防止类的重名问题
2.在项目开发中有很多的类,可以把相同的功能的类放在一个包里,方便管理。
例如:
工具类:com.dream.util/tool
实体类:com.dream.vo/bean/entity
数据库类:com.dream.dao/mapper
具体命名情况参考个人使用情况或者工作安排
static - 静态的
static标识符的作用:
1.修饰属性,表示该属性是静态属性
类加载到方法区时,JVM会扫描该类的所以属性,并把静态属性加载到静态区中,静态属性属于类属性,该类的所有对象共享该属性,静态属性知道项目结束时才被回收。
注意:静态属性使用类名调用;
2.修饰方法,表示该方法时静态方法
属于类方法,直接使用类名调用
package com.Xu.Test1;
public class A {
String str1;
static String str2;
}
package com.Xu.Test1;
public class Text01 {
public static void main(String[] args) {
A a = new A();
A b = new A();
a.str1="1111";
a.str1="2222";
System.out.println(a.str1);
System.out.println(b.str1);
// a.str2="xxx";
// b.str2="ooo";
// System.out.println(a.str2);
// System.out.println(b.str2);
//上面四句等于下面四句,所以最后结果会是“ooo”
A.str2="xxx";
A.str2="ooo";
System.out.println(A.str2);
System.out.println(A.str2);
}
}
111
222
ooo
ooo
多应用于工具类中;
3.静态代码块
静态代码块是类加载到方法区时才会被调用,该代码块只能初始化静态变量
public class A{
static int a;
static int b;
int c;
static{
this.a=1;
this.b=2;
}
}
代码块是创建对象时优于构造方法调用,该代码块可以初始化成员变量和静态变量
public class A{
static int a;
static int b;
int c;
{
this.a=1;
this.b=2;
this.c=3;
}
}
成员变量 vs 静态变量
成员变量:属于对象的变量,每个对象独享一份
静态变量:属于类的变量,每个对象都共享一份
创作不易,每天更新优质内容,各位路过给个关注。。。。