Extend a java class from one file in another java file

前端 未结 4 1198
心在旅途
心在旅途 2020-12-07 13:21

How can I include one java file into another java file?

For example: If I have 2 java file one is called Person.java and one is called Student.ja

4条回答
  •  难免孤独
    2020-12-07 13:48

    What's missing from all the explanations is the fact that Java has a strict rule of class name = file name. Meaning if you have a class "Person", is must be in a file named "Person.java". Therefore, if one class tries to access "Person" the filename is not necessary, because it has got to be "Person.java".

    Coming for C/C++, I have exact same issue. The answer is to create a new class (in a new file matching class name) and create a public string. This will be your "header" file. Then use that in your main file by using "extends" keyword.

    Here is your answer:

    1. Create a file called Include.java. In this file, add this:

      public class Include {
          public static String MyLongString= "abcdef";
      }
      
    2. Create another file, say, User.java. In this file, put:

      import java.io.*;
      
      public class User extends Include {
          System.out.println(Include.MyLongString);
      }
      

提交回复
热议问题