Introduction to OOP Flashcards
What is the purpose of encapsulation in OOP?
Encapsulation protects data by grouping it with related methods into a class, restricting access to internal details. This ensures data integrity and modular, maintainable code.
How do you control access to class fields in Java?
Use the private modifier for fields and provide public getter and setter methods to access or modify them.
What is the difference between a class and an object?
A class is a blueprint for objects, defining properties and methods. An object is an instance of a class, storing actual data and behavior.
When should you use an interface over an abstract class?
Use an interface for defining shared behavior across unrelated classes or when multiple inheritance is needed. Use an abstract class for closely related classes.
What is the role of a constructor in Java?
A constructor initializes an object’s attributes during creation. It has no return type and must match the class name.
What are the main types of constructors in Java?
Default Constructor: No parameters, provided automatically if none is defined.
No-Arg Constructor: Explicitly defined with no parameters.
Parameterized Constructor: Takes arguments to set specific object states.
How does the static keyword improve memory efficiency?
Static variables and methods belong to the class rather than instances, allowing shared memory space and avoiding redundant object creation.
What are the four access modifiers in Java, and where are they accessible?
Public: Accessible everywhere.
Private: Accessible only within the class.
Protected: Accessible within the same package and subclasses.
Default (Package-Private): Accessible only within the same package.
How does abstraction simplify complex systems?
Protects data from unauthorized access.
Ensures code modularity and reusability.
Improves maintainability by hiding implementation details.
What is the difference between a field and a variable?
Field: A data member of a class, used to hold an object’s state.
Variable: A named storage space, which can be local (inside methods) or global (fields).