java编写一个类,里面包含学号,学生姓名两个属性,再编写一个静态函数,可交换两人信息。
4条回答 默认 最新
radium0028 2022-03-08 21:28关注封装类呢?多少个属性都能交换。
package org.example; public class Student { public String name; public String no; public static void swap(StudentWrapper s1, StudentWrapper s2){ Student temp = s1.student; s1.student = s2.student; s2.student = temp; } public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student(); s1.setName("张三"); s1.setNo("1"); s2.setName("李四"); s2.setNo("2"); StudentWrapper sw1 = new StudentWrapper(s1); StudentWrapper sw2 = new StudentWrapper(s2); System.out.println("======转换前======"); System.out.println("s1.getName() = " + sw1.student.getName()); System.out.println("s1.getNo() = " + sw1.student.getNo()); System.out.println("s2.getName() = " + sw2.student.getName()); System.out.println("s2.getNo() = " + sw2.student.getNo()); Student.swap(sw1,sw2); System.out.println("======转换后======"); System.out.println("s1.getName() = " + sw1.student.getName()); System.out.println("s1.getNo() = " + sw1.student.getNo()); System.out.println("s2.getName() = " + sw2.student.getName()); System.out.println("s2.getNo() = " + sw2.student.getNo()); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNo() { return no; } public void setNo(String no) { this.no = no; } static class StudentWrapper{ Student student; StudentWrapper(Student student){ this.student = student; } } }输出结果:
======转换前====== s1.getName() = 张三 s1.getNo() = 1 s2.getName() = 李四 s2.getNo() = 2 ======转换后====== s1.getName() = 李四 s1.getNo() = 2 s2.getName() = 张三 s2.getNo() = 1本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 1无用