Example Code:
/*** e.g 1 ***/
public class A
{
private int a;
}
public class B extends A
{
private int s;
}
/*** e.g 2 ***/
public class C
{
int a;
}
public class E extends C
{
private int s;
}
Ans: e.g 1
Key points about Tightly encapsulated class
- A tightly encapsulated class does not allow direct public access to the internal data model. Instead, access is permitted only through accessor (i.e. get) and mutator (i.e. set) methods. The additional time required to work through the accessor and mutator methods typically slows execution speed.
- A tightly encapsulated class does not allow public access to any data member that can be changed in any way. So encapsulation helps to protect internal data from the possibility of corruption from external influences.
- The mutator methods can impose constraints on the argument values. If an argument falls outside of the acceptable range, then a mutator method could throw an IllegalArgumentException.
- The internal design of a tightly encapsulated class can change while the public interface remains unchanged. An immutable class is always tightly encapsulated, but not every tightly encapsulation class is immutable.
- Encapsulation enhances the maintainability of the code. A tightly encapsulated class allows access to data only through accessor and mutator methods.
- A tightly encapsulated class might have mutator methods that validate data before it is loaded into the internal data model.
- The data members of a tightly encapsulated class are declared private, so changes to the data model are less likely to impact external code.
- Access to internal data can be provided by public accessor (i.e. get) and mutator (i.e. set) methods.