Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 908
Jin Yong Avatar asked May 19 '09 01:05

Jin Yong


People also ask

Can a Java class be extended?

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.

How do I import 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.

Can two Java classes be in the same file?

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.

How do you include a class in Java?

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.


1 Answers

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! 
like image 98
Chris Bunch Avatar answered Sep 21 '22 11:09

Chris Bunch