2.4.6

Encapsulation & Polymorphism

Test yourself

Encapsulation

Encapsulation in object-oriented programming is a principle that concerns how data inside the class can be accessed or changed.

Illustrative background for Setters and gettersIllustrative background for Setters and getters ?? "content

Setters and getters

  • A setter is a special type of method that sets one of the attributes equal to a specific value.
  • A getter is a special type of method that obtains the value of one of the attributes of the object.
Illustrative background for EncapsulationIllustrative background for Encapsulation ?? "content

Encapsulation

  • Each attribute can only be accessed or modified by methods that are set (encapsulated) when defining the class.
    • This is also known as 'information hiding'.
  • The use of these methods protects the data in the class instance from being tampered with.
Illustrative background for Different instancesIllustrative background for Different instances ?? "content

Different instances

  • An instance of a class should not be able to alter the data of another instance of the same class.
  • For example, if you have an instance of a car class called “car1”, its methods should not be able to alter the attributes of another instance of the car class that is also running.

Polymorphism

In object-oriented programming, polymorphism is when a subclass alters its inherited methods in two ways: by overloading or overriding.

Illustrative background for OverloadingIllustrative background for Overloading ?? "content

Overloading

  • Overloading is when a method is defined in the subclass that has the same name, but different arguments to a method defined in the superclass.
  • The method might also have a different return type.
  • For example, a shape superclass might have an area calculating function.
    • The subclass circle could have the function area(radius), whereas a triangle subclass could have the function area(base,height).
Illustrative background for OverridingIllustrative background for Overriding ?? "content

Overriding

  • Overriding is when a method is redefined in the subclass with the same name and same arguments.
  • The method that is defined in the subclass overrides the method defined in the super class.

Jump to other topics

1Components of a Computer

2Software & Software Development

3Exchanging Data

4Data Types, Data Structures & Algorithms

5Legal, Moral, Cultural & Ethical Issues

6Elements of Computational Thinking

6.1Thinking Abstractly

6.2Thinking Procedurally

6.3Thinking Logically

7Problem Solving & Programming

8Algorithms

Go student ad image

Unlock your full potential with GoStudent tutoring

  • Affordable 1:1 tutoring from the comfort of your home

  • Tutors are matched to your specific learning needs

  • 30+ school subjects covered

Book a free trial lesson