Sample questions
Question 1Easy
In Java, which access modifier makes a member visible only within its own class?
- default (package-private)
- private
- public
- protected
Answer: B. private
Explanation
private: same class only. default: same package. protected: same package plus subclasses. public: everywhere.
Step-by-step solution
- Private modifier restricts access to the same class only.
- Default allows access within the same package.
- Protected extends access to subclasses in other packages.
- Public grants access from anywhere in the code.
- The correct answer is private.
Why the other options are wrong
- A. Default access is visible to all classes in the same package, not only within the class itself.
- C. Public access is visible from any class, so it is the widest level and not the one that limits access to the class.
- D. Protected access is visible in the package and to subclasses, which is wider than the class alone.
Tip: Remember: private = same class only.
Question 2Easy
Data hiding is achieved mainly by:
- Declaring fields private and exposing controlled methods
- Making every method static so that no object state is ever needed
- Writing all classes in one file
- Using inheritance
Answer: A. Declaring fields private and exposing controlled methods
Explanation
Private fields cannot be touched from outside; public methods then decide how the data may be read or changed.
Step-by-step solution
- Private fields prevent external access.
- Public methods control data changes.
- This hides internal state from users.
- Methods ensure safe data manipulation.
- Data hiding is achieved through this approach.
Why the other options are wrong
- B. Making every method static removes object state, so it does not hide data inside objects.
- C. File layout does not control access to fields; a single file hides nothing.
- D. Inheritance reuses behaviour across classes; it does not hide fields from callers.
Tip: Use private fields with public methods to hide data effectively.
Question 3Easy
Encapsulation mainly helps a class to:
- Inherit from several parents
- Avoid writing constructors
- Run faster on multi-core machines because private fields need no locking
- Change its internal implementation without breaking the code that uses it
Answer: D. Change its internal implementation without breaking the code that uses it
Explanation
Because callers depend only on the public interface, hidden internals can be refactored freely.
Step-by-step solution
- Encapsulation hides internal data behind a public interface.
- Callers use only the interface.
- So internals can change without breaking callers.
Why the other options are wrong
- A. Multiple inheritance is unrelated to encapsulation.
- B. Constructors are still often needed.
- C. Private fields give no performance gain on multi-core systems.
Question 4Easy
Getter and setter methods are also called:
- Decorators and adapters
- Constructors and destructors
- Accessors and mutators
- Iterators and generators
Answer: C. Accessors and mutators
Explanation
A getter (accessor) reads a field and a setter (mutator) changes it, usually with validation.
Step-by-step solution
- A getter method reads the value of a field.
- A setter method changes the value of a field.
- These methods are called accessors and mutators; the correct answer is option C.
Why the other options are wrong
- A. Decorators and adapters are a different kind of code, not these methods.
- B. Constructors and destructors create and clean up objects.
- D. Iterators and generators are about looping over data.
Tip: Accessor = get, mutator = set.
Question 5Medium
What happens when this Java code is compiled?
class Account {
private int balance;
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
a.balance = 100;
System.out.println(a.balance);
}
}
- It compiles but throws an exception at runtime
- It prints 100
- Compilation error: balance has private access in Account
- It compiles, but balance is silently treated as public, printing 100
Answer: C. Compilation error: balance has private access in Account
Explanation
Private members cannot be accessed from another class, even in the same file. Access is checked at compile time.
Step-by-step solution
- a.balance = 100 tries to access private field balance.
- Java checks access modifiers at compile time only.
- Private fields are not accessible from other classes in the same file.
- This line causes a compilation error.
- The code does not compile, so no runtime exception occurs.
- Final answer: Compilation error: balance has private access in Account.
Why the other options are wrong
- A. The error is found by the compiler, so the code never runs and no runtime exception is thrown.
- B. The code does not compile, so nothing is printed; the private field cannot be accessed from Main.
- D. Java does not treat private fields as public; the access rule is enforced and causes a compilation error.
Tip: Always check access modifiers when accessing variables from other classes.
Question 6Medium
Which design makes an object immutable?
- All methods declared synchronized so that no two threads can change the fields at the same time
- All fields declared public static
- All fields set once in the constructor, no setters, and no exposure of mutable internals
- The class declared abstract
Answer: C. All fields set once in the constructor, no setters, and no exposure of mutable internals
Explanation
An immutable object fixes its state at construction and never lets anyone change it afterwards, including through returned references to mutable fields.
Step-by-step solution
- Immutable objects fix state at construction.
- Fields are set once in constructor.
- No setters allow changes later.
- Mutable internals are not exposed.
- This prevents any future modifications.
- Final answer: All fields set once in the constructor, no setters, and no exposure of mutable internals.
Why the other options are wrong
- A. synchronized methods make calls thread-safe but do not make the object immutable.
- B. Public static fields can still change and are shared, so they do not create immutability.
- D. abstract stops a class being instantiated directly; it does not stop its fields from changing.
Tip: Make all fields final and set them in the constructor to ensure immutability.
Question 7Medium
What does this Python code print?
class Temp:
def __init__(self):
self._c = 0
@property
def c(self):
return self._c
@c.setter
def c(self, v):
if v < -273:
raise ValueError("too cold")
self._c = v
t = Temp()
t.c = 25
try:
t.c = -300
except ValueError as e:
print(t.c, e)
- 25 too cold
- -300 too cold
- 25 ValueError
- 0 too cold
Answer: A. 25 too cold
Explanation
The property setter validates before storing, so the bad value is rejected and _c keeps 25. Printing the exception shows its message.
Step-by-step solution
- The Temp class has a property c with a setter that checks if v < -273.
- t.c = 25 sets _c to 25 without error.
- t.c = -300 triggers the setter, which raises ValueError because -300 < -273.
- The except block prints t.c (still 25) and the exception message 'too cold'.
- So the output is 25 too cold.
Why the other options are wrong
- B. The setter raises before storing the value, so t.c is still 25 and -300 is never printed.
- C. print shows the exception message too cold, not the class name ValueError.
- D. The value 25 was stored first, so t.c is 25 and not 0.
Tip: Remember that property setters run before assignment, so invalid values are rejected.
Question 8Medium
A Java class marks its fields private but every field has a public getter and setter with no checks. What is the main criticism?
- The class will not compile, because private fields can only be read by the class itself
- It violates the Liskov Substitution Principle
- Encapsulation is only nominal: callers can still put the object in any state
- Private fields can't have getters
Answer: C. Encapsulation is only nominal: callers can still put the object in any state
Explanation
Blindly generated setters expose the state almost as much as public fields; real encapsulation exposes behaviour and enforces rules.
Step-by-step solution
- The fields are private, so it compiles and works.
- But a public setter with no checks lets any caller set any value.
- So the object can be put into invalid states, just like with public fields.
Why the other options are wrong
- A. A class's public methods can access its private fields, so it compiles.
- B. LSP is about subtype substitutability, not getters/setters.
- D. Private fields can have getters, and this is the common pattern.
Tip: Getter+setter on everything = encapsulation in name only.
Question 9Hard
A C++ class declares another class as a friend. What is the effect?
- The friend class can access the declaring class's private and protected members
- The declaring class can access the friend's private members
- The friend class inherits from the declaring class
- Both classes share a single vtable
Answer: A. The friend class can access the declaring class's private and protected members
Explanation
Friendship is granted, not taken, and is one-way: only the class named as friend gets access to the granting class's non-public members.
Step-by-step solution
- A class explicitly declares another class (or function) as a friend inside its own body.
- The friend class can then access the declaring class's private and protected members, as if it were a member itself.
- The declaring class gains no special access to the friend in return - friendship is one-way.
Why the other options are wrong
- B. Friendship is not reciprocal - the declaring class does not automatically gain access to the friend's private members.
- C. Being granted friend status has nothing to do with inheritance; the friend class is unrelated in the class hierarchy.
- D. Friendship doesn't involve vtables or any shared virtual-dispatch mechanism at all.
Tip: Friendship is granted, not mutual, and never inherited by subclasses.
Question 10Hard
In Java, can a subclass in a different package access a protected field through a reference of the parent type (not 'this' or a subclass reference)?
- No, protected members aren't inherited across packages at all
- Yes, protected means visible to all subclasses through any reference
- Yes, but only in static methods
- No, access is only through references of the subclass type or its descendants
Answer: D. No, access is only through references of the subclass type or its descendants
Explanation
Outside the package, protected access is allowed only via the subclass's own type (e.g. this or a Sub reference), not via an arbitrary Parent reference.
Step-by-step solution
- Protected fields are accessible in subclasses within the same package.
- Outside the package, protected access is restricted to subclass references only.
- A Parent type reference cannot access protected fields from a different package.
- Access through Parent type is not allowed even if the field is inherited.
- Only subclass or descendant references can access protected members outside the package.
- Final answer: No, access is only through references of the subclass type or its descendants.
Why the other options are wrong
- A. Protected members are inherited, and subclasses in other packages can use them through this.
- B. Protected does not allow any reference; a parent-type reference is refused across packages.
- C. Static methods do not get this extra access; the rule applies to instance references.
Tip: Remember: protected fields are not accessible via parent type references outside the package.
Practise all 22 questions free
The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.
Open this topic in the app →