Chapter 10 Flashcards
(37 cards)
What is an abstract class in Java?
A class that cannot be instantiated and is used as a base for subclasses. It often includes abstract methods with no body.
Can an abstract class be instantiated?
No, you cannot create objects of an abstract class.
How do you declare an abstract class?
Using the abstract
keyword in the class declaration, e.g., public abstract class Product {}
.
Can abstract classes have non-abstract methods?
Yes, abstract classes can include methods with full implementations.
What happens if a subclass doesn’t implement all but some abstract methods from its abstract parent?
Then the subclass must also be declared abstract.
Can abstract methods be static or final?
No, abstract methods cannot be static or final.
How are abstract classes represented in UML?
They are shown in italics.
What is a Java interface?
A collection of abstract methods and constants that define a contract a class must implement.
Can you instantiate an interface?
No, interfaces cannot be instantiated.
What keyword is used to create an interface?
interface
, e.g., public interface Doable {}
How do you implement an interface in a class?
Using the implements
keyword in the class declaration.
Are interface methods public by default?
Yes, all methods in an interface are public by default.
Can a class implement multiple interfaces?
Yes, Java supports multiple interface implementation.
What are the default modifiers for fields in an interface?
All fields are public static final
by default.
What is the purpose of the Comparable interface?
It defines a method compareTo
to allow object comparison for sorting.
What does compareTo return when two objects are equal?
It returns 0.
What does compareTo return if the calling object is less than the other?
It returns a negative number.
What does compareTo return if the calling object is greater than the other?
It returns a positive number.
What Java method can sort a list of Comparable objects?
Collections.sort()
.
When should you use an abstract class?
When classes share code or have protected/private fields or partial implementations.
When should you use an interface?
When unrelated classes need to implement the same method signatures or you want multiple inheritance.
What are differences between abstract classes and interfaces?
Abstract classes can have fields and non-abstract methods; interfaces only have public static final fields and abstract methods.
What is polymorphism?
The ability of a reference variable to change behavior depending on the object it refers to.
What are the two types of polymorphism in Java?
Compile-time (method overloading) and runtime (method overriding).