艾歐踢論壇

標題: Why does java file name must be same as public class name? [打印本頁]

作者: admin    時間: 2020-3-2 14:18
標題: Why does java file name must be same as public class name?
"Can we keep different names for java class name and java file name?"

Yes, we can keep the different name for the java filename and java class name if and only if the class is not public.

There are two cases, that we will discuss here...


Case 1: We are taking different name if the class is not public

With the help of an example, we will see what will happen if the class is not public and in that case, we can take a different name for the java class and java file that means it is not mandatory to have the same name for the java class name and java filename in that case.

Example:
  1. class ClassIsNotPublic{
  2.         public static void main(String[] args){
  3.                 String str1 = "This class is not public so we can take different name for the java filename and java classname";
  4.                 String str2 = "This class is not prefixed with public keyword that's why it is not public";

  5.                 System.out.println("What will happen if we take non public class " +str1);
  6.                 System.out.println("Why it is not public class "+ str2);
  7.         }
  8. }
複製代碼
Output

E:\Programs>javac abc.java [abc is java filename]

E:\Programs>java ClassIsNotPublic [ClassIsNotPublic is java classname]
What will happen if we take non public class This class is not public so
we can take different name for the java filename and java classname
Why it is not public class This class is not prefixed with public keyword
that's why it is not public

Case 2: We are taking different name if the class is public

If we declared a class as "public" then, in that case, java filename and java class name must be same or in other words, we can’t take any other name for the java class name and java filename in the case of a public class.

Example:
  1. public class ClassIsPublic{
  2.         public static void main(String[] args){
  3.                 String str1 = "This class is public so we can't take different name for the java filename and java classname";
  4.                 String str2 = "This class is prefixed with public keyword that's why it is public class";

  5.                 System.out.println("What will happen if we take public class"+" " +str1);
  6.                 System.out.println("Why it is public class "+ str2);
  7.         }
  8. }
複製代碼
Output

E:\Programs>javac xyz.java
xyz.java:1: error: class IfClassIsPublic is public, should be
declared in a file named IfClassIsPublic.java
public class IfClassIsPublic{
       ^
1 error

Now we will see why it is required to take the same name for the java filename and java class name in the case of a public class?

There are few points to understand why it is required to take the same name?









歡迎光臨 艾歐踢論壇 (http://www.iot.idv.tw/ucenter/) Powered by Discuz! X3.2