0

I am new to programming and cannot figure out how to create a new object using a 2-argument constructor. I'm just going to copy/paste code out of the program that is relevant.

This is my class:

public class Car {

    private int yearModel;
    private String make;
    private static int speed;


    public Car (int yM, String m)
    {
        yearModel = yM;
        make = m;
        speed = 0;
    }

This is my test class:

public class TestCar {

    private static String Honda;

    public static void main(String[] args)
    {
        Car c1 = new Car(1999, Honda);

I couldn't run the program without adding "private static String Honda;".

When I run it I get Null for Honda.

2 Answers 2

4

Your constructor takes a string object but the Honda you're passing it is not a string. Try adding double quotes around it if "Honda" is what you want to pass it.

Without the quotes the compiler thinks you are trying to reference a Honda variable but it can't find it. Once you declare the variable with the "private static String Honda" bit then it finds the variable. You still have a problem there though, because Honda isn't set to anything. Either set the Honda variable to some value (preferably "NSX" or "S2000") or just pass that value directly to the constructor (enclosing it in quotes as I mentioned above).

0
0

main() is a static function.. Static functions can not use non static vaiables hence Honda should be static.

Honda has not been initialized so initialize the Honda as follows:

 private static String Honda = "Some String";

or

 private static String Honda = new String("Some String");

Accessing a reference(String Honda) without its object(new String("")) will always lead you to null pointer exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.