What relationship does extends establish in Java?
A superclass is a general class; a subclass is a specialized class that extends it with extends. For example, Car extends Vehicle.
Study Java Inheritance and Polymorphism with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
What relationship does extends establish in Java?
A superclass is a general class; a subclass is a specialized class that extends it with extends. For example, Car extends Vehicle.
How many direct superclasses can a Java class have?
Java supports single inheritance for classes: each class has exactly one direct superclass, except Object at the top of the hierarchy.
Are constructors inherited by subclasses?
Constructors are not inherited. A subclass constructor must initialize the superclass portion, usually by calling an appropriate superclass constructor with super(...).
What does super(...) do in a constructor?
super(...) calls a constructor in the direct superclass and must be the first statement in the subclass constructor. If omitted, Java attempts to insert super().
How do this(...) and super(...) differ?
this(...) calls another constructor in the same class, whereas super(...) calls a constructor in the direct superclass. Either call must be the first statement.
How can a subclass use a private superclass field?
A subclass cannot directly access a private superclass field. It must use an accessible method, such as a public or protected accessor or controlled operation.
What makes a method an override?
A subclass overrides an inherited instance method by using the same name and parameter list, with the same or a covariant return type and no weaker access.
How do overloading and overriding differ?
Overloading uses different parameter lists, usually resolved at compile time. Overriding uses the same parameter list in a subclass and enables runtime polymorphism.
What do reference type and runtime type control?
For Animal pet = new Dog(), the reference type is Animal and the runtime object type is Dog. The reference type controls accessible members; the runtime type selects overridden instance methods.
What does Animal a = new Dog(); a.speak(); execute?
Calling a method through an Animal reference that refers to a Dog runs Dog's overridden instance method. This runtime selection is dynamic dispatch, or late binding.
Why is upcasting safe?
Upcasting assigns a subclass object to a superclass reference, such as Animal animal = dog. It is safe because every subclass object is also a superclass object.
When can a superclass reference be downcast safely?
Downcasting is valid only when the referenced object is actually an instance of the target subclass. Otherwise, the cast can throw ClassCastException; use instanceof when a check is needed.