Java Interview Guide: How to Build Confidence With a Solid Understanding of Core Java Principles pdfdrive com



Yüklə 0,53 Mb.
Pdf görüntüsü
səhifə11/47
tarix06.05.2023
ölçüsü0,53 Mb.
#108601
1   ...   7   8   9   10   11   12   13   14   ...   47
Java Interview Guide

Composition vs Inheritance
Composition and inheritance both provide code reuse, but it can be difficult
to determine which relationship is more appropriate. As a general rule,
ask whether two objects share a HAS-A or an IS-A relationship. For example,
a party HAS-A guest list, so it follows that a Party should be composed
of a List. On the other hand, a student IS-A person, so it follows that
a Student should inherit from a Person.
Although both methods are powerful, they each have their own weaknesses.
Composition requires delegation code and prevents polymorphism unless
additional interfaces are introduced. Inheritance forces a rigid object hierarchy
and tightly couples two classes. When in doubt, composition is the preferred
approach because it’s more flexible than inheritance.


Questions
What is the difference between composition and inheritance?
What is the difference between method overriding and method overloading?
How would you determine whether to use composition or inheritance?


Abstract Classes & Interfaces
Abstract Classes
Abstract classes are designed to be extended and cannot be instantiated.
For example, an abstract class Person might contain common attributes and
rely on concrete subclasses like Employee and Student to provide additional
functionality. An abstract class can have both concrete and abstract methods,
but it can only be instantiated by a concrete subclass that implements every
abstract method somewhere along the object hierarchy.


Interfaces
Interfaces promote polymorphism by describing a form that an object can take.
For example, imagine a government agency that is interested in taxing people.
Rather than tightly couple their codebase to the Student and Employee
objects, they could instead introduce a Taxable interface and require people
to provide their own implementations. Interfaces can only contain constant fields
and empty methods. A class can implement more than one interface, but it must
provide the implementation for every method (duplicate methods are treated
as one).



Yüklə 0,53 Mb.

Dostları ilə paylaş:
1   ...   7   8   9   10   11   12   13   14   ...   47




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin