7. What are constructors in Java? How are they different from methods?
Constructors: Special methods to initialize objects.
Name matches the class.
No return type.
Difference from methods: Methods perform actions; constructors initialize objects.
8. Explain method overloading and method overriding with examples.
Overloading: Same method name, different parameters (compile-time polymorphism).
java CopyEdit
class Example (
void display(int a) ()
void display(String b) ()
}
Overriding: Subclass provides a new implementation for a method in the superclass (runtime polymorphism).
java CopyEdit
class Parent {
void display() {}
} class Child extends Parent (
@Override
void display(){}
}
9. What is inheritance in Java? Discuss its types.
Inheritance allows a class to acquire the properties and methods of another class using the
extends keyword. Types:
1. Single: One class inherits from another.
2. Multilevel: A chain of inheritance.
3. Hierarchical: Multiple classes inherit from one superclass.
4. Multiple (via interfaces): A class implements multiple interfaces.
10. Define polymorphism and its types in Java.
Polymorphism allows methods to perform different tasks based on the object. Types:
1. Compile-time (Method Overloading).
2. Runtime (Method Overriding).
11. What is an interface in Java, and how does it differ from an abstract Class?
Interface: A collection of abstract methods and static constants. Can have default and static methods (since Java 8).
A class can implement multiple interfaces.
Difference:
Abstract class can have both abstract and concrete methods; an interface has abstract methods by default (Java 7 and below).
A class extends one abstract class but can implement multiple interfaces.