Include one java file in another java file

How to include one java file in another java file?

For example: If I have two java files, one is called Person.java and one is Student.java . How to include Person.java in Student.java so that I can extend the class from Person.java to Student.java

+53
java import include
May 19 '09 at 1:58 a.m.
source share
4 answers

Just put two files in one directory. Here is an example:

Person.java

 public class Person { public String name; public Person(String name) { this.name = name; } public String toString() { return name; } } 

Student.java

 public class Student extends Person { public String somethingnew; public Student(String name) { super(name); somethingnew = "surprise!"; } public String toString() { return super.toString() + "\t" + somethingnew; } public static void main(String[] args) { Person you = new Person("foo"); Student me = new Student("boo"); System.out.println("Your name is " + you); System.out.println("My name is " + me); } } 

Starting the Student (since he has the main function) gives us the desired result:

 Your name is foo My name is boo surprise! 
+55
May 19 '09 at 2:07 a.m.
source share
— -

What is missing in all of the explanations is that Java has a strict rule for class name = file name. The value, if you have the class "Person", should be in a file named "Person.java". Therefore, if one class is trying to access the "Person", the file name is optional, since it must be "Person.java".

For C / C ++, I have the same problem. The answer is to create a new class (in a new file corresponding to the class name) and create a public line. This will be your header file. Then use this in your main file using the "extends" keyword.

Here is your answer:

  • Create a file called Include.java. In this file, add the following:

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

     import java.io.*; public class User extends Include { System.out.println(Include.MyLongString); } 
+23
Sep 17 '09 at 19:23
source share

Java does not use, as C. does. Instead, java uses a concept called classpath, a list of resources containing Java classes. The JVM can access any class in the classpath by name, so if you can extend classes and refer to types simply by declaring them. Finishes working with the include statement. Java has an "import". Since classes are split into namespaces such as foo.bar.Baz, if you are in the qux package and want to use the Baz class without using the full name foo.bar.Baz, then you need to use import at the beginning of your java file: import foo.bar.Baz

+19
May 19 '09 at 2:27
source share

No.

If you want to expand Person with Student, simply do:

 public class Student extends Person { } 

And make sure you can find the other when compiling both classes.

What IDE are you using?

+2
May 19, '09 at 2:00
source share



All Articles