1Z0-811 Inheritance and Polymorphism 1 — Questions and Answers
Question 1: Which keyword is used in Java to create a subclass that inherits from a parent class?
- implements
- extends (Correct answer)
- inherits
- super
Correct answer: extends
The 'extends' keyword is used to create a subclass that inherits fields and methods from a parent class.
Question 2: How many classes can a Java class directly extend?
- Only one (Correct answer)
- Up to two
- Up to three
- Unlimited
Correct answer: Only one
Java supports single inheritance for classes, meaning a class can only directly extend one other class.
Question 3: What does calling 'super()' inside a constructor do?
- Creates a new instance of the parent class
- Calls the parent class constructor (Correct answer)
- References the current class instance
- Invokes a static method from the parent
Correct answer: Calls the parent class constructor
When 'super()' is used in a constructor, it calls the parent class's constructor to initialize inherited fields.
Question 4: Which access modifier makes a member accessible to subclasses in different packages but not to unrelated classes?
- private
- public
- protected (Correct answer)
- default
Correct answer: protected
The 'protected' access modifier allows access from subclasses regardless of package and from classes within the same package.
Question 5: Are constructors inherited by subclasses in Java?
- Yes, all constructors are inherited
- No, constructors are not inherited (Correct answer)
- Yes, but only public constructors are inherited
- Yes, but only if the superclass has a no-arg constructor
Correct answer: No, constructors are not inherited
Constructors are not inherited in Java; however, subclasses can call parent constructors using super().
Question 6: What is the implicit parent class of every Java class that does not explicitly extend another class?
- java.lang.Base
- java.lang.Class
- java.lang.Object (Correct answer)
- java.lang.Root
Correct answer: java.lang.Object
Every Java class implicitly extends java.lang.Object if no other parent class is specified.
Question 7: Given: class Animal {} and class Dog extends Animal {}, which statement is true?
- Dog is a type of Animal (Correct answer)
- Animal is a subtype of Dog
- Dog cannot access Animal's public methods
- Animal implicitly extends Dog
Correct answer: Dog is a type of Animal
In an 'is-a' relationship, Dog is a type of Animal because Dog extends Animal, inheriting its behavior.
Which keyword is used in Java to create a subclass that inherits from a parent class?