Extend a java class from one file in another java file

前端 未结 4 1197
心在旅途
心在旅途 2020-12-07 13:21

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.ja

4条回答
  •  醉话见心
    2020-12-07 13:42

    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!
    

提交回复
热议问题