Java As Object Oriented - 1

Encapsulation & private & public

(HL MA 8)

One of the primary concepts of OOP is that both the attributes of a class and the methods that act upon them are together, "encapsulated". And the only way that attributes can be worked with by any other class is via those methods. And so the methods control/manage the way that the attributes can be worked with. In this way, the programmer of a particular class has complete control over how data is worked with.

What allows the encapsulation, the protection of the attributes and the access of them via the methods is what are referred to as "access modifiers", which are the keywords:


private allows only access from within the class. So attributes are "protected" by being made private.

public allows all other classes access, so the methods which will be available to all other classes are made public. Do note that there may indeed be many methods which are private, which means they can only be used by other methods within that class. Such private methods are often referred to as "helper" methods.

protected allows only other classes in the same package to have access. It is usually methods which are protected rather than attributes.

Attributes versus Methods

Basically all programs can be said to be made up of attributes and methods. By attributes we mean the "stuff", i.e. the data which is worked with, and by methods, we are referring to all of the "action" parts of the program, whcih work with the data. In good, encapsulated Object Oriented Programming, all attributes should therefore be private, and most methods will be public.

Constructor Methods

Constructor methods are the special methods which make instances of a certain class, so that data can be worked with via the other methods.