Chris Arnone
Chris Arnone

Reputation: 15

Creating classes in Java

I'm trying to create a class to list information on cars. The two files I have below are CarClass.Java and Car.java.

When running CarClass.Java I am receiving one error on the "Car car1 = new Car(2018, "Black", "Chevy", "Corvette", 250);" line of code.

error: constructor Car in class Car cannot be applied to given types;

required: no arguments

found: int,String,String,String,int

reason: actual and formal argument lists differ in length

1 error

My question is what do I need to change in order to fix this error so my program will run properly?

 import java.io.PrintStream;

public class CarClass
{
   public static void main(String[] args)
   {
      Car car1 = new Car(2018, "Black", "Chevy", "Corvette", 250);


      System.out.println("The " + car1.getYear() + " " + car1.getColor() + " " + car1.getMake() + " " + car1.getModel() + "Top speed is " + car1.getSpeed() + 
      " mph.");
      }
     }



--------------------------------------------------------------------------------

public class Car
{
   private int carYear;
   private String carColor;
   private String carMake;
   private String carModel;
   private int carSpeed;

   public void Car(int year, String color, String make, String model, int speed)
   {


      this.carYear = year;
      this.carColor = color;
      this.carMake = make;
      this.carModel = model;
      this.carSpeed = speed;
   }

   public int getYear()
   {
   return this.carYear;
   }

   public String getColor()
   {
   return this.carColor;
   }

   public String getMake()
   {
   return this.carMake;
   }

   public String getModel()
   {
   return this.carModel;
   }

   public int getSpeed()
   {
   return this.carSpeed;
   }
 }

Upvotes: 1

Views: 169

Answers (3)

Harry D
Harry D

Reputation: 11

You should not use a return statement in a Constructor. A Constructor is used to Initialize your object. So, you don't have the need of returning anything. Hence, the modification below should work.

public Car(int year, String color, String make, String model, int speed)
{
  this.carYear = year;
  this.carColor = color;
  this.carMake = make;
  this.carModel = model;
  this.carSpeed = speed;
}

Upvotes: 0

PDS
PDS

Reputation: 46

The below statement will call the constructor of the class :

Car car1 = new Car(2018, "Black", "Chevy", "Corvette", 250);

But then since you had mentioned a return type in the Car class it will be treated as a method by JVM

public void Car(int year, String color, String make, String model, int speed) {

  this.carYear = year;
  this.carColor = color;
  this.carMake = make;
  this.carModel = model;
  this.carSpeed = speed;

}

remove the return type to solve the error !

Upvotes: 0

Nicholas K
Nicholas K

Reputation: 15423

Your constructor cannot have a return type. Change it to :

public Car(int year, String color, String make, String model, int speed) {

}

Upvotes: 4

Related Questions