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
The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another.
Otherwise, it is very easy. In Eclipse or NetBeans just write the class you want to use and press on Ctrl + Space . The IDE will automatically import the class.
No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than one public classes a single file a compile-time error will be generated.
To import java package into a class, we need to use java import keyword which is used to access package and its classes into the java program. Use import to access built-in and user-defined packages into your java source file so that your class can refer to a class that is in another package by directly using its name.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With