Reputation: 168
So I'm just starting to learn java and have come to this example:
class Dog {
int size;
String breed;
String name;
void bark() {
System.out.println("Ruff! Ruff!");
}
} // class Dog
class DogTestDrive {
public static void main(String[] args) {
Dog d = new Dog();
d.size = 40;
d.bark();
} // end main
} // class DogTestDrive
When I try to run it I get the following error: Error: Main method not found in class Dog, please define the main method as: public static void main(String[] args)
I don't see where is the problem? This should work with only one main mathod.
Upvotes: 1
Views: 214
Reputation: 1427
Your code runs right, but make sure that the file is named "DogTestDrive.java", because you must run it. Further, you should declare the class DogTestDrive as public
(not necessary).
class Dog {
int size;
String breed;
String name;
void bark() {
System.out.println("Ruff! Ruff!");
}
} // class Dog
public class DogTestDrive {
public static void main(String[] args) {
Dog d = new Dog();
d.size = 40;
d.bark();
} // end main
} // class DogTestDrive
Upvotes: -1
Reputation: 425033
When you start java, you tell it which class to execute. Java finds the main()
method in the specified class and calls it.
You need to tell java to execute DogTestDrive
.
Note that if you're executing this in an IDE it's as easy as right-clicking on DogTestDrive
in your project and chiding "Run".
The class java runs must be a "top level" class - that is one that is declared in its own file of the same name as the class, but with .java
added (not a class declared in another class's file).
Upvotes: 3
Reputation: 2359
In Java, each file with a .java
extension has one public class with the same name as the file (e.g. Dog.java
has public class Dog {...
). A file can have multiple classes, but only one can be public
.
When you run a file named Dog.java
, Java will try to execute Dog.main
in the file. If you want DogTestDrive.main
to run then you must put DogTestDrive
in DogTestDrive.java
As for class Dog {...
, can either go in the same file or in its own Dog.java
file, the latter being preferred because then classes outside of the file will be able to access it.
Upvotes: 0
Reputation: 623
What Tim B means is that you have to run DogTestDrive
instead of Dog
. This way the main method from DogTestDrive
is used and no main method in Dog
is needed.
Upvotes: 0