Java_Concepts_Detailed_Answers
Java_Concepts_Detailed_Answers
Types of Inheritance:
1. Single Inheritance – One subclass inherits from one superclass.
2. Multilevel Inheritance – A class inherits from a class which in turn inherits from another
class.
3. Hierarchical Inheritance – Multiple classes inherit from one superclass.
4. Multiple Inheritance (via interfaces) – A class can implement multiple interfaces.
5. Hybrid Inheritance – A combination of multiple types, supported via interfaces.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
Example:
class Student {
String name;
Student(String name) {
this.name = name;
}
}
Example:
class Student {
String name;
int age;
Student(String name) {
this.name = name;
}
Exception Hierarchy:
- Throwable (Root class)
- Error (serious issues like OutOfMemoryError)
- Exception (for exceptional conditions)
- Checked Exceptions (e.g., IOException)
- Unchecked Exceptions (e.g., ArithmeticException, NullPointerException)
Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
Syntax:
try {
// risky code
} catch (ExceptionType name) {
// handling code
} finally {
// cleanup code (optional)
}
Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Cleanup actions.");
}
Collections are in the `java.util` package and support operations like searching, sorting,
insertion, manipulation, and deletion.
These controls are part of `javafx.scene.control` and are added to scenes to build GUIs.
Example:
public class Test {
private int a; // Only inside Test
int b; // Default – package only
protected int c; // Package + subclass
public int d; // Everywhere
}
Example of Overloading:
class Calculator {
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
Example of Overriding:
class Animal {
void sound() { System.out.println("Animal sound"); }
}
Examples:
int age = 25;
float salary = 50000.75f;
char grade = 'A';
boolean passed = true;
String name = "John"; // Reference type