Pushpam Kumar
Pushpam Kumar

Reputation: 82

i'm getting compile time-error when i create class public why?

public class foo{int a;}
public class foo2{public static void main(String[] a){System.out.println("love");}}

The error is:

C:\Users\PUSHPAM\Desktop\java>javac foo2.java foo2.java:1: error: class foo is public, should be declared in a file named foo.java public class foo{

Upvotes: 0

Views: 75

Answers (2)

Anil Reddy Yarragonda
Anil Reddy Yarragonda

Reputation: 767

Suppose if you have multiple classes in single program then you have to save your class with the class which have main() method. And that class should be public type. Don't make all the classes as public in one file.

Example:

class Vehicle {
    //something
}

class Audi {
    //something
}

class Manager {
    public static void main(String[] args) 
    {
      // something
     }
}

main() method is available in Class Manager. Because of this i have to save the file with Manager.java.

javac Manager.java ---- .class files will generate for all the classes

java Manager --- getting output

Upvotes: 0

Sam Estep
Sam Estep

Reputation: 13354

You can only have one public class per Java source file. The name of that file must match the public class name, so if you have a public class called MyClass, it must be in a file called MyClass.java.

Upvotes: 1

Related Questions