6.1 面向对象编程概述(了解)
练习一:声明员工类Employee,包含属性、编号id、姓名name、年龄age、薪资salar 声明员工类Employee,包含属性:岗位attribu、编号id、姓名name、年龄age、薪资salary、生日(MyDate类型) 声明EmployeeTest测试类,并在main方法中,创建两个员工对象,并为属性赋值,并打印两个员工信息 // 为姓名和生日赋值 ++++++++++++++++++++++++++++ 声明MyDate类型,有属性:年(year)、月(month)、日(day)
package com.atczy01.field;
/**
* ClassName: Employee
* Package: atczy03.field_method
* Description:
* 声明员工类Employee,包含属性、编号id、姓名name、年龄age、薪资salary
* @Author Ziyun Chen
* @Create 2023/9/26 6:57
* @Version 1.0
*/
public class Employee {
// 声明成员属性
String attribute;
String id;
String name;
int age;
double salary;
MyDate date;
}
package com.atczy01.field;
/**
* ClassName: EmployeeTest
* Package: atczy03.field_method
* Description:
* 声明员工类Employee,包含属性:岗位attribu、编号id、姓名name、年龄age、薪资salary、生日(MyDate类型)
* 声明EmployeeTest测试类,并在main方法中,创建两个员工对象,并为属性赋值,并打印两个员工信息 // 为姓名和生日赋值
* ++++++++++++++++++++++++++++
* 声明MyDate类型,有属性:年(year)、月(month)、日(day)
* @Author Ziyun Chen
* @Create 2023/9/26 6:57
* @Version 1.0
*/
public class EmployeeTest {
public static void main(String[] argc){
// 类的实例化
Employee e1 = new Employee();
Employee e2 = new Employee();
System.out.println(e1); //类型@地址
e1.attribute = "common";
e1.id = "123456";
e1.name = "wcx";
e1.age = 20;
e1.salary = 20000;
System.out.println(e1.attribute + "\t"+ e1.id + "\t" + e1.name + "\t" + e1.age + "\t" + e1.salary);
e2.attribute = "CEO";
e2.id = "123543";
e2.name = "czy";
e2.age = 18;
e2.salary = 20000;
System.out.println(e1.attribute + "\t"+ e1.id + "\t" + e1.name + "\t" + e1.age + "\t" + e1.salary);
System.out.println(e2.attribute + "\t\t"+ e2.id + "\t" + e2.name + "\t" + e2.age + "\t" + e2.salary);
Employee e3 = new Employee();
e3.name = "chen";
e3.date = new MyDate();
e3.date.year = 2000;
e3.date.month = 1;
e3.date.day = 15;
System.out.println(e3.name + " 生日为: " + e3.date.year + "年" + e3.date.month + "月" + e3.date.day + "日");
Employee e4 = new Employee();
e4.name = "ziyun";
e4.date = new MyDate();
e4.date.year = 2000;
e4.date.month = 1;
e4.date.day = 15;
System.out.println(e4.name + " 生日为: " + e4.date.year + "年" + e4.date.month + "月" + e4.date.day + "日");
}
}
package com.atczy01.field;
/**
* ClassName: My
* Package: atczy03.field_method
* Description:
* 声明MyDate类型,有属性:年(year)、月(month)、日(day)
* @Author Ziyun Chen
* @Create 2023/9/26 7:18
* @Version 1.0
*/
public class MyDate {
int year;
int month;
int day;
}
6.2 Java语言的基本元素:类和对象
(1)创建Person类的对象,设置该对象的name、age和sex属性,调用study方法,输出字符串“studying”,调用showAge()方法显示age值,调用addAge()方法给对象的age属性值增加2岁
package com.atczy02.example.exer01;
/**
* ClassName: Person
* Package: atczy04.example.exer01
* Description:
* (1)创建Person类的对象,设置该对象的name、age和sex属性,调用study方法,输出字符串“studying”,
* 调用showAge()方法显示age值,调用addAge()方法给对象的age属性值增加2岁。
* @Author Ziyun Chen
* @Create 2023/9/27 9:14
* @Version 1.0
*/
public class Person {
String name;
int age;
char sex;
public void study(){
System.out.println("studying");
}
public void showAge(){
System.out.println(age);
}
public void addAge(int add){
age += add;
}
}
(1)创建Person类的对象,设置该对象的name、age和sex属性,调用study方法,输出字符串“studying”,调用showAge()方法显示age值,调用addAge()方法给对象的age属性值增加2岁。 (2)创建第二个对象,执行上述操作,体会同一个类的不同对象之间的关系
package com.atczy02.example.exer01;
/**
* ClassName: PersonTest
* Package: atczy04.example.exer01
* Description:
* (1)创建Person类的对象,设置该对象的name、age和sex属性,调用study方法,输出字符串“studying”,
* 调用showAge()方法显示age值,调用addAge()方法给对象的age属性值增加2岁。
* (2)创建第二个对象,执行上述操作,体会同一个类的不同对象之间的关系
* @Author Ziyun Chen
* @Create 2023/9/27 9:14
* @Version 1.0
*/
public class PersonTest {
public static void main(String[] argc){
Person p1 = new Person();
p1.name = "chen";
p1.age = 22;
p1.sex = '女';
p1.study();
p1.showAge();
p1.addAge(2);
p1.showAge();
}
}
3.1 编写程序,声明一个method方法,在方法中打印一个 10*8的*型矩形 ,在main方法中调用该方法。
3.2 修改上一个程序,在method方法中,除打印一个 10*8的*型矩形外,再计算该矩形的面积,并将其作为方法返回值。在main方法中调用该方法,接收返回的面积值并打印。
3.3 修改上一个程序,在method方法提供m和n两个参数,方法中打印一个 m*n的*型矩形 ,并计算该矩形的面积, 将其作为方法返回值。在main方法中调用该方法,接收返回的面积值并打印。
package com.atczy02.example.exer02;
/**
* ClassName: Exer02
* Package: atczy04.example.exer02
* Description:
* 3.1 编写程序,声明一个method方法,在方法中打印一个 10*8的*型矩形 ,在main方法中调用该方法。
* 3.2 修改上一个程序,在method方法中,除打印一个 10*8的*型矩形外,再计算该矩形的面积,并将其
* 作为方法返回值。在main方法中调用该方法,接收返回的面积值并打印。
* 3.3 修改上一个程序,在method方法提供m和n两个参数,方法中打印一个 m*n的*型矩形 ,并计算该矩
* 形的面积, 将其作为方法返回值。在main方法中调用该方法,接收返回的面积值并打印。
* @Author Ziyun Chen
* @Create 2023/9/27 14:09
* @Version 1.0
*/
public class Exer02 {
public static void main(String[] argc){
Exer02 exer = new Exer02();
int area = exer.method(10,8);
System.out.println("面积为: " + area);
}
public int method(int m, int n){
for (int i = 0; i < m; ++i){
for (int j = 0; j < n; ++j){
System.out.print("*");
}
System.out.println();
}
return m * n;
}
}
利用面向对象的编程方法,设计圆类Circle,包含属性(半径)和计算圆面积的方法。定义测试类,创建该Circle类的对象,并进行测试
package com.atczy02.example.exer03;
/**
* ClassName: Circle
* Package: atczy04.example.exer03
* Description:
* 利用面向对象的编程方法,设计圆类Circle,包含属性(半径)和计算圆面积的方法。定义测试
* 类,创建该Circle类的对象,并进行测试
* @Author Ziyun Chen
* @Create 2023/9/27 14:22
* @Version 1.0
*/
public class Circle {
int r;
public int findArea(){
return 3*r*r;
}
}
package com.atczy02.example.exer03;
/**
* ClassName: Exer03
* Package: atczy04.example.exer03
* Description:
* 利用面向对象的编程方法,设计圆类Circle,包含属性(半径)和计算圆面积的方法。定义测试
* 类,创建该Circle类的对象,并进行测试
* @Author Ziyun Chen
* @Create 2023/9/27 14:19
* @Version 1.0
*/
public class Exer03 {
public static void main(String[] argc){
Circle c = new Circle();
c.r = 3;
System.out.println("面积为: " + c.findArea());
}
}
定义一个操作int[]的工具类
涉及到的方法有:求最大值、最小值、总和、平均数、遍历数组、复制数组、数组反转、数组排序(默认从小到大)、查找等
数组排序的顺序可以进行选择,从大到小,或者从小到大
package com.atczy02.example.exer04;
/**
* ClassName: MyArrays
* Package: atczy04.example.exer04
* Description:
* 定义一个操作int[]的工具类
* 涉及到的方法有:求最大值、最小值、总和、平均数、遍历数组、复制数组、数组反转、数组排序(默认从小到大)、查找等
*
* 数组排序的顺序可以进行选择,从大到小,或者从小到大
* @Author Ziyun Chen
* @Create 2023/9/27 14:32
* @Version 1.0
*/
public class MyArrays {
/**
* 获取int[]数组的最大值
* @param arr 求取最大值的数组
* @return 数组中的最大值
*/
public int findMax(int[] arr){
int max = arr[0];
for (int i = 0; i < arr.length; ++i){
max = max > arr[i] ? max : arr[i];
}
return max;
}
/**
* 获取int[]数组的最小值
* @param arr 求取最小值的数组
* @return 数组中的最大值
*/
public int findMin(int[] arr){
int min = arr[0];
for (int i = 0; i < arr.length; ++i){
min = min > arr[i] ? arr[i] : min;
}
return min;
}
/**
* 获取int[]数组的总和
* @param arr 求取总和的数组
* @return 数组的总和
*/
public int countSum(int[] arr){
int sum = 0;
for (int i = 0; i < arr.length; ++i){
sum += arr[i];
}
return sum;
}
/**
* 获取int[]数组的平均值
* @param arr 求平均值的数组
* @return 数组的平均值
*/
public int countAvg(int[] arr){
return countSum(arr)/arr.length;
}
/**
* 遍历数组int[]
* @param arr 需要遍历的数组
*/
public void iterate(int[] arr){
for (int i = 0; i < arr.length; ++i){
System.out.print(arr[i] + "\t");
}
System.out.println();
}
/**
* 复制int[]数组
* @param arr 需要复制的数组
* @return 复制后的数组
*/
public int[] copy(int[] arr){
int[] arr1 = new int[arr.length];
for (int i = 0; i < arr.length; ++i){
arr1[i] = arr[i];
}
return arr1;
}
/**
* 对int[]数组进行反转
* @param arr 需要反转的数组
*/
public void reverse(int[] arr){
int tmp = 0;
for (int i = 0, j = arr.length-1; i < j; ++i, --j){
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
/**
* 对数组进行排序
* @param arr 需要进行排序的int[]数组
* @return 返回排序后的数组
*/
public int[] sort(int[] arr) {
int tmp = 0;
for (int i = 0; i < arr.length - 1; ++i) {
for (int j = 0; j < arr.length - 1 - i; ++j) {
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
return arr;
}
public int[] sort(int[] arr, String sortMethod) {
if ("asc".equals(sortMethod)){ // ascend
int tmp = 0;
for (int i = 0; i < arr.length - 1; ++i) {
for (int j = 0; j < arr.length - 1 - i; ++j) {
if (arr[j] > arr[j + 1]) {
// tmp = arr[j];
// arr[j] = arr[j + 1];
// arr[j + 1] = tmp;
swap(arr, j, j+1);
}
}
}
} else if("desc".equals(sortMethod)){// descend
int tmp = 0;
for (int i = 0; i < arr.length - 1; ++i) {
for (int j = 0; j < arr.length - 1 - i; ++j) {
if (arr[j] < arr[j + 1]) {
// tmp = arr[j];
// arr[j] = arr[j + 1];
// arr[j + 1] = tmp;
swap(arr, j, j+1);
}
}
}
} else {
System.out.println("排序方式输入有误: " + sortMethod);
}
return arr;
}
public void swap(int[] arr, int i, int j){
int tmp = 0;
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/**
* 寻找arr[]数组中,和num相同元素的索引位置
* @param arr 需要寻找的数组
* @param num 需要找到的元素
* @return 返回元素所在位置
*/
public int search(int[] arr, int num){
int ret = -1;
int i = 0;
for (; i < arr.length; ++i){
if (arr[i] == num){
break;
}
}
ret = i >= arr.length ? -1 : i;
return ret;
}
}
package com.atczy02.example.exer04;
import java.util.Arrays;
/**
* ClassName: Exer04
* Package: atczy04.example.exer04
* Description:
*
* @Author Ziyun Chen
* @Create 2023/9/27 14:46
* @Version 1.0
*/
public class Exer04 {
public static void main(String[] argc){
MyArrays m_arr = new MyArrays();
int[] arr = new int[]{1,2,3,4};
System.out.println("数组为:" + Arrays.toString(arr));
System.out.println("最大值为:" +m_arr.findMax(arr));
System.out.println("最小值为:" +m_arr.findMin(arr));
System.out.println("总和为:" +m_arr.countSum(arr));
System.out.println("平均值为:" +m_arr.countAvg(arr));
m_arr.reverse(arr);// 对数组进行反转
System.out.println("反转后数组为:" + Arrays.toString(arr));
System.out.println("排序后数组为:" + Arrays.toString(m_arr.sort(arr)));
System.out.println("从小到大排序后数组为:" + Arrays.toString(m_arr.sort(arr, "asc")));
System.out.println("从大到小排序后数组为:" + Arrays.toString(m_arr.sort(arr, "desc")));
System.out.println("复制的数组为:" + Arrays.toString(m_arr.copy(arr)));
System.out.println("查找:" + 2 + "在数组中的索引为: " + m_arr.search(arr, 2));
}
}
定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。 创建20个学生对象,
学号为1到20,年级和成绩都由随机数确定。
问题一:打印出3年级(state值为3)的学生信息。
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
提示:
1) 生成随机数:Math.random(),返回值类型double;
2) 四舍五入取整:Math.round(double d),返回值类型long
package com.atczy02.example.exer05;
/**
* ClassName: Student
* Package: atczy04.example.exer05
* Description:
* 定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。 创建20个学生对象,
* 学号为1到20,年级和成绩都由随机数确定。
* 问题一:打印出3年级(state值为3)的学生信息。
* 问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
* 提示:
* 1) 生成随机数:Math.random(),返回值类型double;
* 2) 四舍五入取整:Math.round(double d),返回值类型long。
* @Author Ziyun Chen
* @Create 2023/9/28 9:13
* @Version 1.0
*/
public class Student {
int number;// 学号
int state;// 年级
int score;// 成绩
}
package com.atczy02.example.exer05;
/**
* ClassName: StudentTest
* Package: atczy04.example.exer05
* Description:
* 定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。 创建20个学生对象,
* 学号为1到20,年级和成绩都由随机数确定。
* 问题一:打印出3年级(state值为3)的学生信息。
* 问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
* 提示:
* 1) 生成随机数:Math.random(),返回值类型double;
* 2) 四舍五入取整:Math.round(double d),返回值类型long。
* @Author Ziyun Chen
* @Create 2023/9/28 9:16
* @Version 1.0
*/
public class StudentTest {
public static void main(String[] argc){
Student[] students = new Student[20];
// 创建学生对象
for (int i = 0; i < students.length; ++i){
students[i] = new Student();
students[i].number = i + 1;
students[i].state = (int)Math.round(Math.random()*(6-1) + 1);// 1~6
students[i].score = (int)Math.round(Math.random()*(100-60) + 60);// 60~100
}
// 打印出3年级(state值为3)的学生信息。
StudentUtil util = new StudentUtil();
util.printStudentWithState(students, 3);
util.printStudent(students);// 打印数组元素信息
// 使用冒泡排序按学生成绩排序,并遍历所有学生信息
util.sort(students);
util.printStudent(students);
}
}
package com.atczy02.example.exer05;
/**
* ClassName: StudentUtil
* Package: atczy04.example.exer05
* Description:
*
* @Author Ziyun Chen
* @Create 2023/9/28 9:46
* @Version 1.0
*/
public class StudentUtil {
/**
* 打印指定年级的学生信息
* @param students 学生信息数组
* @param state 需要打印的年级
*/
public void printStudentWithState(Student[] students, int state){
for (int i = 0; i < students.length; ++i){
if (students[i].state == state){
System.out.println(state + " 年级学生信息为: " + "number = " + students[i].number + " state = " +
students[i].state + " score = " + students[i].score);
}
}
}
/**
* 打印学生数组元素信息
* @param students 需要打印的数组元素信息
*/
public void printStudent(Student[] students){
for (int i = 0; i < students.length; ++i){
System.out.println("按学生成绩排序后的学生信息" + " number =" + students[i].number + " state = " +students[i].state + " score = " + students[i].score);
}
}
public void sort(Student[] students){
Student tmp = students[0];
for (int i = 0; i < students.length - 1; ++i){
for (int j = 0; j < students.length - 1 - i; ++j){
if (students[j].score > students[j+1].score){
tmp = students[j];
students[j] = students[j+1];
students[j+1] = tmp;
}
}
}
}
}
6.3 类的作用区域
面向对象完成具体功能的操作的三步流程 步骤一:创建类,并设计类的内部成员(变量和函数) 步骤二:创建类的对象。 步骤三:通过对象,调用内部声明的属性或方法,完成相关功能
package com.atczy03.field_method;
/**
* ClassName: PhoneTest
* Package: atczy01.oop
* Description:
* 面向对象完成具体功能的操作的三步流程
* 步骤一:创建类,并设计类的内部成员(变量和函数)
* 步骤二:创建类的对象。
* 步骤三:通过对象,调用内部声明的属性或方法,完成相关功能
* @Author Ziyun Chen
* @Create 2023/9/25 11:55
* @Version 1.0
*/
public class PhoneTest {
public static void main(String[] argc){
// 创建类的对象
Phone p1 = new Phone();
p1.name = "huawei";
p1.price = 6999.1;
System.out.println("name = " + p1.name + "price = " + p1.price);
// 调用方法
p1.call();
p1.sendMessage("有内鬼,终止交易");
p1.playGame();
}
}
package com.atczy03.field_method;
/**
* ClassName: Phone
* Package: atczy01.oop
* Description:
* 创建类
* @Author Ziyun Chen
* @Create 2023/9/25 11:55
* @Version 1.0
*/
public class Phone {
// 成员变量
String name; // 收集品牌
double price; // 价格
// 成员函数
public void call(){// 打电话功能
System.out.println("打出电话");
}
public void sendMessage(String message){
System.out.println("发出信息: " + message);
}
public void playGame(){
System.out.println("玩游戏");
}
}
6.4 更多方法
6.4.1 函数重载
package com.atczy05.method_more._01overload;
/**
* ClassName: OverLoadExer
* Package: atczy05.method_more.exer01
* Description:
* 判断与 void show(int a,char b,double c){} 构成重载的有:
* a)void show(int x,char y,double z){} // no
* b)int show(int a,double c,char b){} // yes
* c) void show(int a,double c,char b){} // yes
* d) boolean show(int c,char b){} // yes
* e) void show(double c){} // yes
* f) double show(int x,char y,double z){} // no
* g) void shows(){double c} // no
* @Author Ziyun Chen
* @Create 2023/9/28 10:10
* @Version 1.0
*/
public class OverLoadExer {
}
编写程序,定义三个重载方法并调用。
方法名为mOL。
三个方法分别接收一个int参数、两个int参数、一个字符串参数。
分别执行平方运算并输出结果,相乘并输出结果,输出字符串信息。
在主类的main ()方法中分别用参数区别调用三个方法
package com.atczy05.method_more._01overload;
/**
* ClassName: OverLoadExer01
* Package: atczy05.method_more.exer01
* Description:
* 编写程序,定义三个重载方法并调用。
* 方法名为mOL。
* 三个方法分别接收一个int参数、两个int参数、一个字符串参数。
* 分别执行平方运算并输出结果,相乘并输出结果,输出字符串信息。
* 在主类的main ()方法中分别用参数区别调用三个方法
* @Author Ziyun Chen
* @Create 2023/9/28 10:12
* @Version 1.0
*/
public class OverLoadExer01 {
public static void main(String[] argc){
OverLoadExer01 exer = new OverLoadExer01();
exer.mOL(10);
exer.mOL(10, 11);
exer.mOL("abc");
}
public void mOL(int i){
System.out.println(i*i);
}
public void mOL(int i, int j){
System.out.println(i*j);
}
public void mOL(String str){
System.out.println(str);
}
}
定义三个重载方法max(),
第一个方法求两个int值中的最大值,
第二个方法求两个double值中的最大值,
第三个方法求三个double值中的最大值,并分别调用三个方法
package com.atczy05.method_more._01overload;
/**
* ClassName: OverLoadExer02
* Package: atczy05.method_more.exer01
* Description:
* 定义三个重载方法max(),
* 第一个方法求两个int值中的最大值,
* 第二个方法求两个double值中的最大值,
* 第三个方法求三个double值中的最大值,并分别调用三个方法。
* @Author Ziyun Chen
* @Create 2023/9/28 10:18
* @Version 1.0
*/
public class OverLoadExer02 {
public static void main(String[] argc){
OverLoadExer02 exer = new OverLoadExer02();
System.out.println(exer.max(10,11));
System.out.println(exer.max(1.3,1.6));
System.out.println(exer.max(13.6,14.6, 15.9));
}
public int max(int i, int j){
return i > j ? i : j;
}
public double max(double i, double j){
return i > j ? i : j;
}
public double max(double i, double j, double k){
double m2 = max(i, j);
return max(m2, k);
}
}
6.4.2 参数
n个字符串进行拼接,每一个字符串之间使用某字符进行分割,如果没有传入字符串,那么返回空字符串""
package com.atczy05.method_more._02argc;
/**
* ClassName: StringConCatTest
* Package: atczy05.method_more.exer02
* Description:
* n个字符串进行拼接,每一个字符串之间使用某字符进行分割,如果没有传入字符串,那么返回空字符串""
* @Author Ziyun Chen
* @Create 2023/10/4 13:45
* @Version 1.0
*/
public class StringConCatTest {
public static void main(String[] argc){
// 1.传入n个字符
StringConCatTest arr = new StringConCatTest();
String info = arr.concat("@", "abc", "xzy");
info = arr.concat("@");
info = arr.concat("@", "abc");
System.out.println(info);
}
// 2.对字符进行接收--使用数组
public String concat(String operate, String ... arr){
// 2.1 如果数组为空,返回""
if (arr.length == 0)
return "";
String ret = arr[0];// 返回值
// 2.2 不为空,进行拼接 -- arr[i] + operate + arr[i+1]
for (int i = 1; i < arr.length; ++i){
ret += operate;
ret += arr[i];
}
return ret;
}
}
6.4.3 值传递
package com.atczy05.method_more._03valuetransfer;
/**
* ClassName: ValueTransferTest
* Package: atczy05.method_more._03valuetransfer
* Description:
*
* @Author Ziyun Chen
* @Create 2023/10/4 15:49
* @Version 1.0
*/
public class ValueTransferTest {
public static void main(String[] argc){
// 1.对于基本数据类型的变量
ValueTransferTest test = new ValueTransferTest();
int m = 10;
test.method1(m);
System.out.println(m);// 10
// 2.对于引用数据类型的变量
Person p = new Person();
p.age = 10;
test.method2(p);
System.out.println(p.age);// 11
}
public void method1(int m){
++m;
}
public void method2(Person p){
++p.age;
}
}
class Person{
int age;
}
6.4.4 练习题
定义一个Circle类,包含一个double型的radius属性代表圆的半径,一个findArea()方法返回圆的面积
package com.atczy05.method_more.exer1;
/**
* ClassName: Circle
* Package: atczy05.method_more.exer1
* Description:
* 定义一个Circle类,包含一个double型的radius属性代表圆的半径,一个findArea()方法返回圆的面积
* @Author Ziyun Chen
* @Create 2023/10/4 16:09
* @Version 1.0
*/
public class Circle {
public static void main(String[] argc){
Circle c = new Circle();
c.radius = 1.5;
System.out.println(c.findArea());
}
double radius;
public double findArea(){
return Math.PI*radius*radius;
}
}
定义一个类PassObject,在类中定义一个方法printAreas(),该方法定义如下:
public void printArea(Circle c, int time)
在printAreas方法中打印输出1到time之间的每个整数半径值,以及对应的面 积。例如,times为5,则输出半径1,2,3,4,5,以及对应的圆面积。
(3)在main方法中调用printAreas()方法,调用完毕后输出当前半径值。程序运行结果如图所示。
package com.atczy05.method_more.exer1;
/**
* ClassName: PassObject
* Package: atczy05.method_more.exer1
* Description:
* 定义一个类PassObject,在类中定义一个方法printAreas(),该方法定义如下:
* public void printArea(Circle c, int time)
*
* 在printAreas方法中打印输出1到time之间的每个整数半径值,以及对应的面
* 积。例如,times为5,则输出半径1,2,3,4,5,以及对应的圆面积。
* (3)在main方法中调用printAreas()方法,调用完毕后输出当前半径值。程序运行结果如图所示。
* @Author Ziyun Chen
* @Create 2023/10/4 16:17
* @Version 1.0
*/
public class PassObject {
public static void main(String[] argc){
PassObject p = new PassObject();
Circle c = new Circle();
p.printArea(c, 6);
}
public void printArea(Circle c, int times){
for (int i = 1; i <= times; ++i){
c.radius = i;
System.out.println(c.radius + "\t" + c.findArea());
}
System.out.println("now radius is " + c.radius);
}
}
走台阶问题
假如有10阶台阶,小朋友每次只能向上走1阶或者2阶,请问一共有多少种的不同走法?
阶数: 1 2 3 4 5 ...
走法: 1 2 3 5 8 ...
f(n) = f(n-1)+f(n-2)
package com.atczy05.method_more.exer2;
/**
* ClassName: Footstep
* Package: atczy05.method_more.exer2
* Description:
* 走台阶问题
* 假如有10阶台阶,小朋友每次只能向上走1阶或者2阶,请问一共有多少种的不同走法?
*
* 阶数: 1 2 3 4 5 ...
* 走法: 1 2 3 5 8 ...
*
* f(n) = f(n-1)+f(n-2)
* @Author Ziyun Chen
* @Create 2023/10/6 11:00
* @Version 1.0
*/
public class Footstep {
public static void main(String[] argc){
Footstep test = new Footstep();
System.out.println(test.getStep(5));
}
public int getStep(int s){
if (s == 1){
return 1;
}else if(s == 2){
return 2;
}else {
return getStep(s-1) + getStep(s-2);
}
}
}
计算斐波那契数列(Fibonacci)的第n个值,斐波那契数列满足如下规律,
1 1 2 3 5 8 ...
f(n) = f(n-1) + f(n-2)
package com.atczy05.method_more.exer2;
/**
* ClassName: RabbitExer
* Package: atczy05.method_more.exer2
* Description:
* 计算斐波那契数列(Fibonacci)的第n个值,斐波那契数列满足如下规律,
* 1 1 2 3 5 8 ...
* f(n) = f(n-1) + f(n-2)
* @Author Ziyun Chen
* @Create 2023/10/6 10:34
* @Version 1.0
*/
public class RabbitExer {
public static void main(String[] argc){
RabbitExer r = new RabbitExer();
System.out.println(r.getRabbitNumber(24));
}
public int getRabbitNumber(int month){
if (month == 1){
return 1;
} else if(month == 2){
return 1;
} else{
return (getRabbitNumber(month-1) + getRabbitNumber(month-2));
}
}
}
6.5 封装性
练习1:
创建程序:在其中定义两个类:Person和PersonTest类。定义如下:
用setAge()设置人的合法年龄(0~130),用getAge()返回人的年龄。
在PersonTest类中实例化Person类的对象b,调用setAge()和getAge()方法,体会Java的封装性
package com.atczy06.encapsulation.exer1;
/**
* ClassName: PersonTest
* Package: com.atczy09.encapsulation.exer1
* Description:
* 练习1:
* 创建程序:在其中定义两个类:Person和PersonTest类。定义如下:
* 用setAge()设置人的合法年龄(0~130),用getAge()返回人的年龄。
* 在PersonTest类中实例化Person类的对象b,调用setAge()和getAge()方法,体会Java的封装性
* @Author Ziyun Chen
* @Create 2023/10/6 19:31
* @Version 1.0
*/
public class PersonTest {
public static void main(String[] argc){
Person b = new Person();
b.setAge(200);
System.out.println(b.getAge());
}
}
class Person{
private int age;
// 设置age属性
public void setAge(int a){
if (a >= 0 && a <= 130)
age = a;
else
System.out.println("输入有误:");
}
// 获取age属性
public int getAge(){
return age;
}
}
package com.atczy06.encapsulation.exer1;
/**
* ClassName: PersonTest
* Package: com.atczy09.encapsulation.exer1
* Description:
* 练习1:
* 创建程序:在其中定义两个类:Person和PersonTest类。定义如下:
* 用setAge()设置人的合法年龄(0~130),用getAge()返回人的年龄。
* 在PersonTest类中实例化Person类的对象b,调用setAge()和getAge()方法,体会Java的封装性
* @Author Ziyun Chen
* @Create 2023/10/6 19:31
* @Version 1.0
*/
public class PersonTest {
public static void main(String[] argc){
Person b = new Person();
b.setAge(200);
System.out.println(b.getAge());
}
}
class Person{
private int age;
// 设置age属性
public void setAge(int a){
if (a >= 0 && a <= 130)
age = a;
else
System.out.println("输入有误:");
}
// 获取age属性
public int getAge(){
return age;
}
}
自定义图书类。设定属性包括:书名bookName,作者author,出版社名publisher,价格price;方法包括:相应属性的get/set方法,图书信息介绍等。
package com.atczy06.encapsulation.exer2;
/**
* ClassName: Book
* Package: com.atczy09.encapsulation.exer2
* Description:
* 自定义图书类。设定属性包括:书名bookName,作者author,出版社名publisher,价格price;方法包
* 括:相应属性的get/set方法,图书信息介绍等。
*
* @Author Ziyun Chen
* @Create 2023/10/6 19:41
* @Version 1.0
*/
public class Book {
private String bookName;
private String author;
private double price;
// 设置书的信息
public void setBookName(String bn) {
bookName = bn;
}
public String getBookName() {
return bookName;
}
public void setAuthor(String a) {
author = a;
}
public String getAuthor() {
return author;
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
}
package com.atczy06.encapsulation.exer2;
/**
* ClassName: BookTest
* Package: com.atczy09.encapsulation.exer2
* Description:
*
* @Author Ziyun Chen
* @Create 2023/10/6 20:31
* @Version 1.0
*/
public class BookTest {
public static void main(String[] argc){
Book book = new Book();
book.setBookName("Java学习");
book.setAuthor("Ziyun Chen");
book.setPrice(66.66);
System.out.println("book name:" + book.getBookName() + ", author:" + book.getAuthor() + ", price:" + book.getPrice());
}
}
声明员工类Employee,
-包含属性:姓名、性别、年龄、电话、属性私有化
-提供get、set方法
-提供String getInfo()方法
package com.atczy06.encapsulation.exer3;
/**
* ClassName: Employee
* Package: com.atczy09.encapsulation.exer3
* Description:
* 声明员工类Employee,
* -包含属性:姓名、性别、年龄、电话、属性私有化
* -提供get、set方法
* -提供String getInfo()方法
* @Author Ziyun Chen
* @Create 2023/10/6 20:39
* @Version 1.0
*/
public class Employee {
private String name;
private char gender;
private int age;
private String tel;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getInfo(){
return name + "\t" + gender + "\t" + age + "\t" + tel;
}
}
package com.atczy06.encapsulation.exer3;
import java.util.Scanner;
/**
* ClassName: EmployeeTest
* Package: com.atczy09.encapsulation.exer3
* Description:
*
* @Author Ziyun Chen
* @Create 2023/10/6 20:48
* @Version 1.0
*/
public class EmployeeTest {
public static void main(String[] argc){
// 创建Employee[]
Employee[] employees = new Employee[2];
Scanner scanner = new Scanner(System.in);
// 添加员工
for (int i = 0; i < employees.length; ++i){
employees[i] = new Employee();
System.out.println("----------添加第" + (i+1) + "员工信息-----------");
System.out.print("姓名:");
employees[i].setName(scanner.next());
System.out.print("性别:");
employees[i].setGender(scanner.next().charAt(0));
System.out.print("年龄:");
employees[i].setAge(scanner.nextInt());
System.out.print("电话:");
employees[i].setTel(scanner.next());
}
// 输出员工信息
for (int i = 0; i < employees.length; ++i){
System.out.println("----------员工列表-----------");
System.out.println("编号" + "\t" + "姓名" + "\t" + "性别" + "\t" + "年龄" + "\t" + "电话");
System.out.println(i+1 + "\t" + employees[i].getName() + "\t" + employees[i].getGender() + "\t" + employees[i].getAge() + "\t" + employees[i].getTel());
// System.out.println(employees[i].getInfo());
}
}
}
6.6 构造器
(1)定义Student类,有4个属性: String name; int age; String school; String major;
(2)定义Student类的3个构造器:
第一个构造器Student(String n, int a)设置类的name和age属性;
第二个构造器Student(String n, int a, String s)设置类的name, age 和school属性;
第三个构造器Student(String n, int a, String s, String m)设置类的name, age ,school和major属性;
(3)在main方法中分别调用不同的构造器创建的对象,并输出其属性值。
package com.atczy07.constructor;
/**
* ClassName: StudentTest
* Package: com.atczy07.constructor
* Description:
* (1)定义Student类,有4个属性: String name; int age; String school; String major;
* (2)定义Student类的3个构造器:
* 第一个构造器Student(String n, int a)设置类的name和age属性;
* 第二个构造器Student(String n, int a, String s)设置类的name, age 和school属性;
* 第三个构造器Student(String n, int a, String s, String m)设置类的name, age ,school和major属性;
* (3)在main方法中分别调用不同的构造器创建的对象,并输出其属性值。
* @Author Ziyun Chen
* @Create 2023/10/7 10:14
* @Version 1.0
*/
public class StudentTest {
public static void main(String[] argc){
Student s1 = new Student("Ziyun Chen", 18);
System.out.println(s1.getInfo());
Student s2 = new Student("Ziyun Chen", 18, "Ocean University of China");
System.out.println(s2.getInfo());
Student s3 = new Student("Ziyun Chen", 18, "Ocean University of China", "Communication");
System.out.println(s3.getInfo());
}
}
class Student{
String name;
int age;
String school;
String major;
Student(String n, int a){
name = n;
age = a;
}
Student(String n, int a, String s){
name = n;
age = a;
school = s;
}
Student(String n, int a, String s, String m){
name = n;
age = a;
school = s;
major = m;
}
public String getInfo(){
return name + "\t" + age + "\t" + school + "\t" + major;
}
}
编写两个类,TriAngle和TriAngleTest,其中TriAngle类中声明私有的底边长base和高height,同时声明公共方法访问私有变量。此外,提供类必要的构造器。另一个类中使用这些公共方法,计算三角形的面积。
package com.atczy07.constructor;
/**
* ClassName: TriAngle
* Package: com.atczy07.constructor
* Description:
* 编写两个类,TriAngle和TriAngleTest,其中TriAngle类中声明私有的底边长base和高height,同时
* 声明公共方法访问私有变量。此外,提供类必要的构造器。另一个类中使用这些公共方法,计算三角形
* 的面积。
* @Author Ziyun Chen
* @Create 2023/10/7 10:22
* @Version 1.0
*/
public class TriAngleTest {
public static void main(String[] argc){
TriAngle ta = new TriAngle(2, 6);
System.out.println(ta.getArea());
}
}
class TriAngle{
private double base;
private double height;
TriAngle(double b, double h){
base = b;
height = h;
}
public double getBase(){
return base;
}
public double getHeight(){
return height;
}
public double getArea(){
return base*height/2;
}
}
1、写一个名为Account的类模拟账户。该类的属性和方法如下图所示。
该类包括的属性:账号id,余额balance,年利率annualInterestRate;
包含的方法:访问器方法(getter和setter方法),取款方法withdraw(),存款方法deposit()。2、创建Customer类。
a. 声明三个私有对象属性:firstName、lastName和account。
b. 声明一个公有构造器,这个构造器带有两个代表对象属性的参数(f和l)
c. 声明两个公有存取器来访问该对象属性,方法getFirstName和getLastName返回相应的属性。
d. 声明setAccount 方法来对account属性赋值。
e. 声明getAccount 方法以获取account属性3.写一个测试程序。
(1)创建一个Customer ,名字叫 Jane Smith, 他有一个账号为1000,余额为2000元,年利率为 1.23% 的账户。
(2)对Jane Smith操作。 存入 100 元,再取出960元。再取出2000元。 打印出Jane Smith 的基本信息
package com.atczy07.constructor.exer03;
/**
* ClassName: Account
* Package: com.atczy07.constructor.exer03
* Description:
* 1、写一个名为Account的类模拟账户。该类的属性和方法如下图所示。
* 该类包括的属性:账号id,余额balance,年利率annualInterestRate;
* 包含的方法:访问器方法(getter和setter方法),取款方法withdraw(),存款方法deposit()。
* @Author Ziyun Chen
* @Create 2023/10/7 10:50
* @Version 1.0
*/
public class Account {
private String id;
private double balance;
private double annualInterestRate;
public Account(String i, double b, double a){
id = i;
balance = b;
annualInterestRate = a;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
// 取款方法
public void withdraw(double money){
if (money > balance){
System.out.println("由于取款数额大于余额,取款失败!");
}else {
balance -= money;
System.out.println("成功取出" + money);
}
}
// 存款方法
public void deposit(double money){
balance += money;
System.out.println("成功存入" + money);
}
}
package com.atczy07.constructor.exer03;
/**
* ClassName: Customer
* Package: com.atczy07.constructor.exer03
* Description:
* 创建Customer类。
* a. 声明三个私有对象属性:firstName、lastName和account。
* b. 声明一个公有构造器,这个构造器带有两个代表对象属性的参数(f和l)
* c. 声明两个公有存取器来访问该对象属性,方法getFirstName和getLastName返回相应的属性。
* d. 声明setAccount 方法来对account属性赋值。
* e. 声明getAccount 方法以获取account属性
* @Author Ziyun Chen
* @Create 2023/10/7 11:00
* @Version 1.0
*/
public class Customer {
private String firstName;
private String lastName;
private Account account;
public Customer(String f, String l){
firstName = f;
lastName = l;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setAccount(Account account) {
if (account == null){
return;
}
this.account = account;
}
public Account getAccount() {
return account;
}
}
package com.atczy07.constructor.exer03;
/**
* ClassName: test
* Package: com.atczy07.constructor.exer03
* Description:
* 3.写一个测试程序。
* (1)创建一个Customer ,名字叫 Jane Smith, 他有一个账号为1000,余额为2000元,年利率为 1.23% 的账户。
* (2)对Jane Smith操作。 存入 100 元,再取出960元。再取出2000元。 打印出Jane Smith 的基本信息
* @Author Ziyun Chen
* @Create 2023/10/7 11:12
* @Version 1.0
*/
public class test {
public static void main(String[] argc){
Customer customer = new Customer("Jane", "Smith");
// (1) 创建一个Customer
// 匿名对象
// 1.匿名对象往往只能被调用一次
// 2.匿名对象常常作为实参传递给方法的形参
customer.setAccount(new Account("1000", 2000, 0.0123));
// (2)对Jane Smith操作
customer.getAccount().deposit(100);
customer.getAccount().withdraw(960);
customer.getAccount().withdraw(2000);
//输出: Customer [Smith, Jane] has a account: id is 1000, annualInterestRate is 1.23%, balance
//is 1140.0
System.out.println("Customer[ " + customer.getLastName() + ", " + customer.getFirstName()
+ "] has a account: id is " + customer.getAccount().getId() + ", annualInterestRate is " + customer.getAccount().getAnnualInterestRate()*100
+ "%, balance is " + customer.getAccount().getBalance());
}
}
6.6 bean_uml
package com.atczy09.bean_uml;
/**
* ClassName: UserTest
* Package: com.atczy09.bean_uml
* Description:
*
* @Author Ziyun Chen
* @Create 2023/10/7 13:51
* @Version 1.0
*/
public class UserTest {
public static void main(String[] argc){
User u1 = new User(5);
}
}
class User{
String name;
int age = 10;
public User(){}
public User(int a){
age = a;
}
}