What is inheritance in Java?
A
Creating objects from classes
B
The ability of a class to acquire properties and behaviors from another class
C
Creating multiple classes
Analysis & Theory
Inheritance allows one class (subclass) to acquire fields and methods from another class (superclass).
Which keyword is used to inherit a class in Java?
Analysis & Theory
The `extends` keyword is used for class inheritance in Java.
What is the output?
```java
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}```
Analysis & Theory
Since `Dog` inherits `Animal`, it can call the `sound()` method from `Animal`.
What is the term for the class that is inherited from?
C
Parent class or Superclass
Analysis & Theory
The class being inherited from is called the parent class or superclass.
Which of the following types of inheritance is supported in Java?
A
Multiple inheritance using classes
C
Hybrid inheritance using classes
Analysis & Theory
Java supports single and multilevel inheritance using classes.
Can a subclass override a private method of the superclass?
B
Only if it's declared static
C
No, private methods are not inherited
Analysis & Theory
Private methods are not visible to subclasses, so they cannot be overridden.
Which keyword is used to refer to the superclass constructor or method?
Analysis & Theory
`super` is used to call superclass methods and constructors.
What is method overriding in Java?
A
Using the same method name but different parameters
B
Changing a method’s body in the superclass
C
Providing a new implementation of a superclass method in a subclass
D
Calling a method from another class
Analysis & Theory
Overriding means redefining a superclass method in the subclass with the same signature.
What will be the output?
```java
class A {
void show() { System.out.println("A"); }
}
class B extends A {
void show() { System.out.println("B"); }
}
public class Main {
public static void main(String[] args) {
A obj = new B();
obj.show();
}
}```
Analysis & Theory
Dynamic method dispatch calls the overridden `show()` in class B, even though reference is of type A.
Which of the following is NOT true about inheritance?
B
It allows method overriding
C
It supports multiple inheritance with classes
D
It allows subclass to access public and protected members of superclass
Analysis & Theory
Java does NOT support multiple inheritance using classes to avoid ambiguity.