latest articles

Recent Posts Widget

Encapsulation (QCM1 Answered)

01.Correct Options are : A B C

Explanation:
An invariant means a certain condition that constrains the state stored in the object. For example, in this case the value of the area field of the Triangle must always be consistent with its base and height fields. Thus, it should never have a value that is different from base*height/2.
If you allow other classes to directly change the value of base, height, or area, using direct field access, the area field may not contain the correct area thereby breaking the invariant.
To prevent this inconsistency from happening, you need to prohibit changing the instance fields directly and instead permit the changes only through the setter method because these methods call the updateArea method and keep the area and base and height consistent.
02.Correct Option is : C

Explanation:
Encapsulation is one of the 4 fundamentals of OOP (Object Oriented Programming).
Encapsulation means that the internal representation of an object is generally hidden from view outside of the object's definition. Typically, only the object's own methods can directly inspect or manipulate its fields. Some languages like Smalltalk and Ruby only allow access via object methods, but most others (e.g. C++ or Java) offer the programmer a degree of control over what is hidden, typically via keywords like public and private.
Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state. A benefit of encapsulation is that it can reduce system complexity, and thus increases robustness, by allowing the developer to limit the interdependencies between software components.
03.Correct Options are : A B C D

Explanation:
There can be multiple ways to accomplish this. The exam asks you questions on the similar pattern.
The key is that your data variable should be private and the functionality that is to be
exposed outside should be public. Further, your setter methods should be coded such
that they don't leave the data members inconsistent with each other.
Back to Question without Answer
04.Correct Option is : D

Explanation:
When a class is properly encapsulated, only the members that are part of its public API are publicly accessible to other classes. Rest is all private or protected.
05.Correct Option is : E

Explanation:
setRadius method makes sure that radiusB is set to sum - radiusA. So changing sum to 200 should do it. However, note that radiusA, radiusB, and sum are public which means that any other class can access these fields directly without going through the setRadius method. So there is no way to make sure that the value of radiusB is correctly set at all times. If you make them private now, other classes that are
accessing the fields directly will break.
The class should have been coded with proper encapsulation of the fields in the first place.

1 commentaire: