Question 41
MediumWhen should you choose an abstract class over an interface in Java?
- A.
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Object-Oriented Programming
When should you choose an abstract class over an interface in Java?
When unrelated classes need a common capability
When related classes share code or state that the base can provide
When you need multiple inheritance of types
Never
Sign up free to see the answer and a step-by-step explanation.
Since Java 8, which can an interface contain?
Abstract, default and static methods
Instance fields
Constructors
Only abstract methods
Sign up free to see the answer and a step-by-step explanation.
A class implements an interface but doesn't implement all its abstract methods. What must the class be?
Nothing; it compiles anyway
Declared static
Declared abstract
Declared final
Sign up free to see the answer and a step-by-step explanation.
Can you declare a variable of an abstract class type in Java, such as Shape s;?
Only if it is static
No, never
Only inside the abstract class
Yes, it can refer to any concrete subclass object
Sign up free to see the answer and a step-by-step explanation.
Which is an example of abstraction in everyday software?
Writing everything in main()
Using a List interface without knowing whether it's an ArrayList or LinkedList
Making all fields public
Copying code into every class
Sign up free to see the answer and a step-by-step explanation.
class Shape { public: virtual double area() = 0; }; Which line then fails to compile?
Shape s;
Shape &r = someCircle;
Shape *p = nullptr;
class Circle : public Shape { double area() override { return 1; } };
Sign up free to see the answer and a step-by-step explanation.
What is the difference between abstraction and encapsulation?
Encapsulation is a design idea; abstraction is a keyword
They are exactly the same
Abstraction is only for interfaces; encapsulation only for classes
Abstraction hides complexity by showing only what is needed; encapsulation hides data by bundling it with methods and restricting access
Sign up free to see the answer and a step-by-step explanation.
Can an abstract class have no abstract methods in Java?
Only if it has a constructor
No, it must have at least one
Yes; it just can't be instantiated
Only if it is final
Sign up free to see the answer and a step-by-step explanation.
Can an abstract method be private in Java?
No; it must be overridable by subclasses
Yes
Only if it is static
Only in interfaces
Sign up free to see the answer and a step-by-step explanation.
Why can't an abstract method be final?
It can be
final forbids overriding, but an abstract method must be overridden
final methods must be static
Abstract methods must be private
Sign up free to see the answer and a step-by-step explanation.