1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 8. File Handling


Lesson Objective

  • Understand the basics of Object Oriented Programming.
  • Define a Class.
  • Set attribute and create methods.
  • Understand the basics of Encapsulation.
  • Instantiate an Object.
  • Use Constructors to create objects and set values.
  • Understand Inheritance.
  • Understand Polymorphism.

Lesson Notes

Procedural Programming

Procedural programming is a style of programming that divides a program into a set of subroutines.

Data is stored in variables and functions operate on that data.

This style of programming is simple and straightforward, but as programs grow, it can become difficult to manage. Procedural code can become difficult to understand and maintain.

Object-oriented programming (OOP) came to solve this problem.

Groups of related variables and subroutines are grouped together into classes.

A class specifies all the attributes and methods.

Classes become blueprints for objects and define how objects will look and what they do.

......

Code:

Main.java
public class Main {
    public static void main(String[] args) {
        Student stu1 = new Student();
        stu1.name = "Ahmed";
        stu1.age = 15;
        Student stu2 = new Student();
        stu2.name = "Victor";
        stu2.age = 16;
        System.out.println(stu1.name());
    }
}
Student Class
public class Student {
    String name;
    int age;
}

Cmd Output:

Ahmed

Encapsulation

All attributes and methods are wrapped in the class.

By doing this attributes can only be changed through the associated class methods.

Attributes should only be visible in the scope of the class. This is referred to as “data hiding” as implementation details are hidden from the user. This is a key aspect of OOP.

Code:

Main.java
public class Main {
    public static void main(String[] args) {
        Student stu1 = new Student();
        stu1.setName("Ahmed");
        System.out.println(stu1.getName());
        // Method is used to access the attribute.
    }
}
Student Class
public class Student {
    private String name;
    private int age;
    // Attributes set to private so they can only be accessed in the class.
    public String getName() {
        return name;
    }
    public void setName(String n) {
        name = n;
    }
    // Methods have been created to access the name attribute.
}

Cmd Output:

Ahmed
3