0719(012天 面向对象基础02-封装)
每日一狗(边牧coffee的一家)
主标题
文章目录
1. 面向对象基础02(封装)
类:用户自定义的数据类型
- 成员属性:数据
- 成员方法:操作
关键字:class
类名规范:首字母大写,分词首字母大写。
class stu{
// 属性
int stuId;
int name;
// 操作
void gaiMing(){
}
}
对象:类的实例化
- 变量(可命名存储空间)
- 研究目标
对象的属性和方法能不能直接访问修改取决于范围限定词
类名 变量名 = new 类名();
对象的属性使用方法赋值,可以在方法内部进行合法性检验。
一般情况下对象的属性都是私有的,当要把一个属性设定为公共的话,为该对象添加对应的
get、set
方法
限定词 | 当前类内 | 同包 | 子类 | 到处可见 |
---|---|---|---|---|
private | T | |||
无范围限定 | T | T | ||
protected | T | T | T | |
public | T | T | T | T |
练习题:
1. 封装输出员工信息
声明员工类Employee,包含属性:编号、姓名、年龄、薪资,并在main方法中,创建2个员工对象,并为属性赋值,并打印两个员工的信息。
package com.ketang;
public class MyDate {
private int year, month, day;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
if (month > 12) {
this.year += month / 12;
this.month = month % 12;
} else if (month < 1) {
int y = 0;
while (month < 1) {
y--;
month += 12;
}
this.year += y;
this.month = month;
} else {
this.month = month;
}
}
public int getDay() {
return day;
}
public void setDay(int day) {
if (day < 1 || day > 31) {
System.out.println("非法字符");
return;
}
this.day = day;
}
@Override
public String toString() {
return "出生日期是" + year + "年" + month + "月" + day + "日";
}
public void show() {
System.out.println("日期是" + year + "年" + month + "月" + day + "天");
}
}
====================================================================package com.ketang;
public class Test01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Empoyee e1 = new Empoyee();
e1.setBianHao(1);
e1.setNianLing(20);
e1.setXingMing("小黄");
e1.setXinZi(8000);
e1.show(); // 员工1的编号:1,姓名:小黄,年龄:20,薪资:8000.0
Empoyee e2 = new Empoyee();
e2.setBianHao(2);
e2.setNianLing(21);
e2.setXingMing("小兰");
e2.setXinZi(9000);
e2.show(); // 员工2的编号:2,姓名:小兰,年龄:21,薪资:9000.0
}
}
2. 自定义日期类
声明员工类Employee,包含属性:编号、姓名、年龄、薪资,
并在main方法中,创建2个员工对象,并为属性赋值,并打印两个员工的信息。
package com.ketang;
public class MyDate {
private int year, month, day;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
if (month > 12) {
this.year += month / 12;
this.month = month % 12;
} else if (month < 1) {
int y = 0;
while (month < 1) {
y--;
month += 12;
}
this.year += y;
this.month = month;
} else {
this.month = month;
}
}
public int getDay() {
return day;
}
public void setDay(int day) {
if (day > 31) {
while (true) {
if (day <= auxiliaryDay()) {
break;
}
day -= auxiliaryDay();
this.setMonth(++month);
}
} else if (day < 1) {
while (true) {
if (day >= auxiliaryDay()) {
break;
}
day += auxiliaryDay();
this.setMonth(++month);
}
}
this.day = day;
}
public int auxiliaryDay() {
int res = 0;
switch (month