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
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!