1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 9. OOP - Polymorphism


Lesson Objective

  • Understand Polymorphism.

Lesson Notes

Polymorphism

Polymorphism, which translates to "many forms," arises when we have multiple classes connected through inheritance.

Inheritance enables the acquisition of attributes and methods from another class.

Polymorphism, in turn, utilizes these inherited methods to carry out alternate but similar tasks. This flexibility permits the execution of a single action in different ways.

Main.java

public class Main {
    public static void main(String[] args) {
        P16_Student stu24 = new P16_Student("Fei",17,false);
        System.out.print(stu24.getName());
        System.out.print(" is ");
        System.out.println(stu24.getAge());
        System.out.println("UCAS complete: "+stu24.getUCAS());
        stu24.validAge();

        P16_Student stu25 = new P16_Student("Bram",12,false);
        stu25.validAge();

        Student stu1 = new Student ("Bram", 12);
        stu1.validAge();
    }
}

public class Student {
    private String name;
    private int age;
    public Student (String n, int a){
        name = n;
        age = a;
    }
    public void validAge(){
        if (age >=11 && age <= 16) {
            System.out.println("Age Valid");
        }else{
            System.out.println("Age Invalid");
        }
    }
    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.

public class P16_Student extends Student{
    private boolean UCAS;

  public P16_Student(String n,int a,boolean u){
       super (n,a);
       UCAS = u;
   }
   //@Override?
   public void validAge(){
    if (super.getAge() >=16 && super.getAge() <= 19){
         System.out.println("Age Valid");
     }else{
         System.out.println("Age Invalid");
     }
   }
   public boolean getUCAS() {
       return UCAS;
   }
   public void setUCAS(boolean u) {
       UCAS = u;
   }
}

Cmd Output:

Fei is 17
UCAS complete: false
Age Valid
Age Invalid
Age Valid
3