Search code examples
javainitializationsetterinstance-variables

How to set / get a name to "ford" - instance of class Car I have created in main method of class Vehicle?


As you can see I am stuck in part where I should set a name an owner of ford... Thanks for help.

public class Vehicle {

    Person owner;
    long motorSerialNo;
    String registerNo;

    public static void main(String[] args) {

        //an example, create an object instance of class Car

        Car ford           = new Car();
        ford.model         = "Focus";
        ford.motorSerialNo = 123456;
        ford.registerNo    = "CA-126-65";

        //and here is a problem

        ford.owner.setName("John Croul");


    }

}

class Car extends Vehicle {

    String model;

}

class Person {

    public Person(String name){
        this.name = name;
    }
    String name;
    String lastname;
    String address;

    String getName() {
        return name;
    }

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

Solution

  • Firstly, your setter should look like

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

    Then you have to initialize the instance variable person before calling its method setName(), otherwise you will get the NullPoiterException.

    Person owner = new Person();
    

    or in the main method, as you did for other variables

    ford.owner = new Person();