Day - 4 - Nested Loop (10), Define Scope of A Variable (10), Object Orientation, Encapsulation, Abstraction Etc., (15)
Day - 4 - Nested Loop (10), Define Scope of A Variable (10), Object Orientation, Encapsulation, Abstraction Etc., (15)
Topic:
Nested Loop (10), Define Scope of a Variable (10), Object Orientation, encapsulation, Abstraction etc., (15),
Know How to read and write object fields (15),
Nested Loops
A nested loop in Java is a loop inside another loop. The inner loop will complete all its iterations for each iteration of the outer
loop.
Syntax:
java
Example:
java
Explanation:
The outer loop runs 3 times, and for each iteration, the inner loop runs 3 times, resulting in 9 outputs in total.
Scope of a Variable
The scope of a variable in Java defines the region of the program where the variable is accessible. Java has three types of variable
scopes:
Example:
java
Encapsulation
Encapsulation is the concept of wrapping data (variables) and methods that operate on the data into a single unit, called a class. It
also restricts direct access to some of an object’s components, which is a way of hiding the internal state of the object.
Example:
java
Explanation:
The name variable is private, meaning it cannot be accessed directly from outside the class. Instead, you use getter and
setter methods.
Abstraction
Abstraction involves hiding complex implementation details and showing only the essential features of an object. It's achieved
using abstract classes and interfaces.
Example:
java
Explanation:
Animal is an abstract class with an abstract method sound(). The Dog class provides the implementation for the
sound() method.
Reading and writing object fields refers to accessing and modifying the attributes of an object.
Example:
java
Explanation:
The model field of the Car class is accessed directly. The field is assigned a value ("Tesla Model S"), and then it's
read using the displayModel() method.
Summary
Nested Loops: A loop inside another loop, allowing complex iteration patterns.
Variable Scope: Defines where a variable can be accessed within the code.
Encapsulation: Wrapping data and methods into a single unit and restricting access.
Abstraction: Hiding implementation details and showing only the essential features.
Reading/Writing Object Fields: Accessing and modifying the attributes of an object using direct access or methods.