1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 8. Inheritance


Lesson Objective

  • Understand Inheritance.

Lesson Notes

Inheritance

In Java, it is possible to inherit attributes and methods from one class to another. The "inheritance concept" is categorized into two groups:

In Java, to inherit from a class, use the extends keyword.

In the following example, the P16_Student class (subclass) inherits the attributes and methods from the Student class (superclass)

Main.java

public class Main {
    public static void main(String[] args) {
       P16_Student stu24 = new P16_Student();
       stu24.setName("Fei");
       stu24.setAge(17);
       System.out.print(stu24.getName());
       System.out.print(" is ");
       System.out.println(stu24.getAge());
    }
}
// New class inherits from Student superclass.

Student Class

public class Student {
    private String name;
    private int age;
    // Note: Constructor has been removed in this example.
    public String getName() {
        return name;
    }
    public void setName(String n) {
        name = n;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int a) {
        age = a;
    }
}

P16_Student Class

public class P16_Student extends Student{

}

Cmd Output:

Fei is 17

super is used to refer to the superclass, which will send data to the constructor in the superclass to the subclass.

Main.java

public class Main {
  public static void main(String[] args) {
      P16_Student stu24 = new P16_Student("Fei",17,false);
      System.out.println(stu24.getName()+" is "+stu24.getAge());
      System.out.println("UCAS complete: "+stu24.getUCAS());
    }
}
// Method specific to the P16_Student Class used here.

Student Class

public class Student {
    private String name;
    private int age;
    public Student (String n, int a){
        name = n;
        age = a;
    }
    public String getName() {
        return name;
    }
    public void setName(String n) {
        name = n;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int a) {
        age = a;
    }
}
// Original Student Constructor has been placed back into the Student Class.

P16_Student Class

public class P16_Student extends Student{
    private boolean UCAS;

  public P16_Student(String n,int a,boolean u){
       super (n,a);
       UCAS = u;
   }
   public boolean getUCAS() {
       return UCAS;
   }
   public void setUCAS(boolean u) {
       UCAS = u;
   }
}
// New P16_Student Constructor has been created in this class. super is used to specify which parameters are inherited from the student superclass.

Cmd Output:

Fei is 17
UCAS complete: false

3