Search code examples
javasuper

Passing an object to a superclass in Java


For an assignment I'm supposed to have a constructor that takes name, address, phone, make, model, capacity, and numAxles as arguments. The first five should be passed to the superclass, Vehicle. The UML says that my superclass should take the object "person" as the first argument (which is from another class and takes name, address, and phone). How do I pass as argument the name, address, and phone to the superclass from the Truck constructor?

Here's the UML

The Truck class

public Truck(Person person, String make, String model, int year, int mileage, int capacity, int numAxles){
        super(person, make, model, year, mileage);

    }

    public Truck(String name, String address, String phone, String make, String model, int capacity, int numAxles ){
        super(name, address, phone, make, model);
    }

The Vehicle superclass

public Vehicle(Person person, String make, String model, int year){
        setMileage(0);
    }

Solution

  • You can do this by constrcuting a new Person

    super(new Person(name, address, phone), make, model, 2020);
    

    You will probably need some default number for the year as you have not provided it.