自学内容网 自学内容网

Java继承练习

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

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 + '\'' +
                '}';
    }
}


原文地址:https://blog.csdn.net/m0_66130067/article/details/143531032

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!