jDataLab

2 minute read

In designing objects in information sytems, determining relationships between objects is a skill which a designer or analyst must master. One common relationship type is the Generalization/Specification type. The type defines a hierarchy which consists of a superclass and multiple subclasses. A subclass inherits everything from its superclass, which is referred to as inheritance in the object-orientation methodology and object-oriented programming. By inheritance, the superclass’s attributes will not repeat in any of its subclasses. When a new object of subclass is created, no extra object of the superclass is needed.

The following Java code shows you how to implement two classes: Person and Student. Student inherits all the attributes, fname and lname, as well as the methods, initializer and toString, from Person. In addition, Student has its own attribute: year.

https://repl.it/@axoloti/InheritanceJava

Source code

public class Person {    
    private String fname;
    private String lname;
    public Person(String fname, String lname) {
        this.fname = fname;
        this.lname = lname;
    }
    public String toString() {
        return getClass().getName() + ": " + this.fname +" " + this.lname; 
    }
}
public class Student extends Person{    
    private int year;
    public Student(String fname, String lname, int year) {
        super(fname, lname);
        this.year = year;
    }
    public String toString() {
        return super.toString()+"\n"+"year: "+ this.year; 
    } 
}
class Main {
  public static void main(String[] args) {
    Person person = new Person("Alice","Joker");
    System.out.println(person.toString());

    Student student1 = new Student("Jimmy","Dean", 2019);
    System.out.println(student1.toString());

    Student student2 = new Student("Ba","Ba", 2018);
    System.out.println(student2.toString());

    Student student3 = new Student("Mo","Ma", 2017);
    System.out.println(student3.toString());
  }
}