Untitled Document
Untitled Document
PIET CSE AI
1. Introduction to Java
2. Control Statements
3. Inheritance
4. Strings
5. Interface
6. Multithreading
7. Arrays
21.What is an ArrayIndexOutOfBoundsException?
This exception occurs when you try to access an array element using an invalid index.
8. Collections
25.What is Encapsulation ?
Encapsulation is the bundling of data (variables) and methods (functions) that operate on the
data into a single unit, i.e., a class. It also restricts direct access to some of the object's
components, which is known as data hiding.
Example:
You can make fields private and provide public getter and setter methods to access and update
the value.
class Person {
private String name; // Encapsulation: private variable
public String getName() { // Getter method
return name;
}
Definition: Abstraction means hiding complex implementation details and showing only the
necessary functionality. It allows you to focus on what an object does rather than how it does it.
Example:
Using abstract classes and interfaces to define methods without implementing them.
Definition: Inheritance is the mechanism by which one class (child or subclass) inherits fields
and methods from another class (parent or superclass). This allows for code reusability and
establishing relationships between classes.
Example:
A Dog class can inherit properties and behaviors from an Animal class.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
Definition: Polymorphism allows one entity (method or object) to take many forms. It is achieved
through method overloading (compile-time) and method overriding (run-time).
Example:
Method Overloading (compile-time polymorphism) – same method name, different parameters.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
Aggregation: It's a special form of association where one class (whole) contains objects of
another class (part). The part can exist independently of the whole. For example, a Department
and a Professor—a department can have many professors, but professors can exist
independently of the department.
Composition: It's a stronger form of aggregation where the part cannot exist without the whole.
For example, a Car and its Engine—if the car is destroyed, the engine ceases to exist as well.