Extend a java class from one file in another java file
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.java
. How can I include Person.java
into Student.java
so that I can extend the class from Person.java
in Student.java
Solution 1:
Just put the two files in the same directory. Here's 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);
}
}
Running Student (since it has the main function) yields us the desired outcome:
Your name is foo
My name is boo surprise!
Solution 2:
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:
-
Create a file called Include.java. In this file, add this:
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); }