Java继承练习

构建Person类(属性:名字、年龄、工作岗位),创建三个对象,并且根据对象的年龄或名字长度来进行冒泡排序

java 复制代码
package chapter08.homework.test01;

public class homework01 {
    public static void main(String[] args) {
        Person[] persons = new Person[3];
        persons[0] = new Person("tom",66,"软件工程师");
        persons[1] = new Person("jack",20,"java工程师");
        persons[2] = new Person("smith",21,"python工程师");
        for (int i = 0; i < persons.length; i++) {
            System.out.println(persons[i]);//默认调Person的toString方法
        }
        Person tem = null;
        for (int i = 0; i < persons.length-1; i++) {
            for (int j = 0; j < persons.length-1-i; j++) {
                //前面人的年龄小于后面的,就交换
//                if (persons[i].getAge()>persons[i+1].getAge()) {
//                   tem=persons[i];
//                    persons[i]=persons[i+1];
//                    persons[i+1]= tem;
//                }
                //按照名字长度排序
                if (persons[i].getName().length()>persons[i+1].getName().length()) {
                    tem=persons[i];
                    persons[i]=persons[i+1];
                    persons[i+1]= tem;
                }
            }
        }
        System.out.println("*********************");
        for (int i = 0; i < persons.length; i++) {

            System.out.println(persons[i]);//默认调Person的toString方法
        }
    }
}
class Person{
    private String name;
    private int age;
    private String job;

    public Person(String name, int age, String job) {
        this.name = name;
        this.age = age;
        this.job = job;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", job='" + job + '\'' +
                '}';
    }
}
相关推荐
程序无bug9 分钟前
手写Spring框架
java·后端
程序无bug11 分钟前
Spring 面向切面编程AOP 详细讲解
java·前端
软件黑马王子16 分钟前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon17 分钟前
C#读写文件:多种方式详解
开发语言·数据库·c#
悠悠小茉莉22 分钟前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
全干engineer22 分钟前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Da_秀26 分钟前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte32 分钟前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
m0_6256865536 分钟前
day53
python
GodKeyNet1 小时前
设计模式-责任链模式
java·设计模式·责任链模式