java面向对象两个对象数组示例


以下是一个简单的Java面向对象示例,其中包含两个对象数组:

class Person {
    String name;
    int age;

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

public class Example {
    public static void main(String[] args) {
        Person[] family1 = new Person[3];
        family1[0] = new Person("Alice", 32);
        family1[1] = new Person("Bob", 28);
        family1[2] = new Person("Charlie", 10);

        Person[] family2 = new Person[2];
        family2[0] = new Person("Dave", 45);
        family2[1] = new Person("Eve", 40);

        // Print out the names and ages of all people in both families
        for (Person person : family1) {
            System.out.println(person.name + " is " + person.age + " years old.");
        }

        for (Person person : family2) {
            System.out.println(person.name + " is " + person.age + " years old.");
        }
    }
}

在这个例子中,我们定义了一个Person类,每个Person对象都有一个名字和年龄。我们创建了两个Person对象数组,family1family2,分别代表两个家庭。在每个数组中,我们使用new关键字实例化了一些Person对象并将它们存储在数组中。然后我们循环遍历数组,打印出每个人的名字和年龄。

以下是另一个Java面向对象示例,其中包含两个不同的对象数组:

class Car {
    String make;
    String model;
    int year;

    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    public void start() {
        System.out.println(make + " " + model + " started.");
    }
}

class Truck {
    String make;
    String model;
    int year;
    int towingCapacity;

    public Truck(String make, String model, int year, int towingCapacity) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.towingCapacity = towingCapacity;
    }

    public void start() {
        System.out.println(make + " " + model + " started.");
    }

    public void tow() {
        System.out.println(make + " " + model + " is towing.");
    }
}

public class Example {
    public static void main(String[] args) {
        Car[] cars = new Car[2];
        cars[0] = new Car("Honda", "Civic", 2021);
        cars[1] = new Car("Toyota", "Corolla", 2022);

        Truck[] trucks = new Truck[1];
        trucks[0] = new Truck("Ford", "F-150", 2023, 12000);

        // Start all vehicles
        for (Car car : cars) {
            car.start();
        }

        for (Truck truck : trucks) {
            truck.start();
        }

        // Tow with the truck
        trucks[0].tow();
    }
}

在这个例子中,我们定义了两个类,CarTruck,每个类都有不同的属性和方法。我们创建了两个对象数组,carstrucks,其中cars包含两个Car对象,trucks包含一个Truck对象。我们通过new关键字实例化了一些对象并将它们存储在数组中。

然后我们循环遍历每个数组,并调用start()方法启动每个车辆。我们还调用trucks[0].tow()方法使卡车拖车。


原文链接:codingdict.net