Error: could not find or load main class Vehicle

rania949

Honorable
Mar 4, 2013
2
0
10,510
Hello,
i am new at Java and i am trying to create a class called Vehicle but everytime i try to call it the error "could not find or load main class Vehicle" is shown. even though i try to find mistakes in my code i can not. The code is:
public class Vehicle
{
String make;
String color;
boolean engineState;

void startEngine()
{
if (engineState == true)
System.out.println("The engine is already on!");
else
{
engineState = true;
System.out.println("The engine is now on.");
}
}

void showAttributes()
{
System.out.println("This vehicle is a " + color + "
" + make);
if (engineState == true)
System.out.println("The engine is on.");
else
System.out.println("The engine is off.");
}

public static void main(String args[])
{
// Create a new vehicle and set its attributes.
Vehicle car = new Vehicle();
car.make = "Rolls Royce";
car.color = "Midnight blue";
System.out.println("Calling showAttributes ...");
car.showAttributes();

System.out.println("--------");
System.out.println("Starting the engine ...");
car.startEngine();
System.out.println("--------");
System.out.println("Calling showAttributes ...");
car.showAttributes();

// Let’s try to start the engine again.
System.out.println("--------");
System.out.println("Starting the engine ...");
car.startEngine();

}
}
 

Ijack

Distinguished
I don't think that calling a class's constructor from within that class's main() function (i.e, creating an instance of the class within the class definition) is going to work. Try separating your program into two classes - Vehicle and (for example) Test Vehicle; the latter will be the one with a main() function and will create an instance of Vehicle.
 

randomizer

Distinguished
It makes sense for your Vehicle class to be able to start its engine and show its attributes. It doesn't make sense for it to be in charge of running your application. You should put the main() method in a class that is named something else (probably the name of your application, or just something generic like Program) and leave the others in Vehicle.

When you are thinking about what should go into your class, think about the real world object it (often) represents. What does your object have (its attributes) and what can it do (its methods)? If a method does something that seems unrelated or only vaguely related to that object, another class is probably needed to contain it instead.

The actual error might be due to having your class path set incorrectly.