oop-examples/lessons/Encapsulation.md
2020-05-24 17:04:37 +02:00

1.1 KiB

Encapsulation

Encapsulation is a simple lesson, this one is not gonna need any code examples.

There are typically 3 keywords you need for encapsulation: private, protected and public.

Private

Private methods and fields are only acessible from within the same class, they can't be read or written from outside.

Protected

Protected is just like private, but descendant classes can access them.

Public

Public is accessible from anywhere.

The static modifier

Static is another one of those keywords, although it doesn't really control access to fields and methods. Anything with the static keyword can be used without an instance of the class. That means you can directly access with with Class.property instead of creating an instance of that class first. This is used for example in java for the main method, since it needs to be accessible without running any of the programs code first.

Encapsulation is not a safety feature, it's only to make clear, which properties should be used by others. Methods like reflection and directly reading/writing memory can still access private or protected properties.