Picture this - you’re at a car dealership and you’re eager to purchase your first car. You settle on a brand new Honda Civic, and your representative asks: sedan or hatchback?

Some folks might consider making a venn diagram to compare and contrast a sedan with a hatchback. It might look something like this:

Screen Shot 2023-11-21 at 9.28.33 AM

While there are a few differences between a sedan and a hatchback, these two types of cars are actually very similar. They perform many of the exact same functions in the exact same way. They have the same engine, same technological features, same safety measures, etc. If we were to restructure our conversation around code, we’d say that sedans and hatchbacks inherit many of the properties common to all cars. The car, in this context, will be our parent class.

Let’s implement a Civic parent class

 

Screen Shot 2023-11-21 at 9.28.55 AM

The Car class has many useful methods that both sedans and hatchbacks need to use.

Now, let’s take a look at the sedan and hatchback classes:

Screen Shot 2023-11-21 at 9.29.02 AM

Notice, in this example, we are implementing an override. This is because while Hatchbacks and Cars both can pop their trunks, they do it in slightly different ways. The trunk of your sedan will be its own storage area, whereas the hatchback will connect to the main interior of the car. It’s important to be careful when using overrides, as your method signatures and return types should be identical to your parent class. The override is an annotation that signals to the compiler that you are modifying code from the parent class.

Screen Shot 2023-11-21 at 9.29.10 AM

Finally, let’s take a look at our main class 

Screen Shot 2023-11-21 at 9.29.16 AM

Notice that our sedan and hatchback instantiation declares both Sedan and Hatchback as a Civic. This is an example of polymorphism, or a way of coding generically that allows for the instances of related classes to be declared as a similar type. If we execute the code, we can see that the turnOn() method, which is declared in the civic parent class, will print equivalent statements for both types of cars despite the fact that Sedan and Hatchback are different subclasses. However, they have unique method declarations for their popTrunk() method, and will have their own print statements.

Screen Shot 2023-11-21 at 9.29.25 AM

In this specific example, if you were to declare Sedan as "sedanCar = new Sedan()" this would not cause any issues, and the code would compile and execute the same. However, polymorphism allows for code to be extensible, as you can pass anything that is a civic as an instance to other methods. One way to demonstrate this principle would be implementing a driver class that has a move civic method. This person can have a drive method that accepts any type Civic as a parameter:

Screen Shot 2023-11-21 at 9.29.32 AM

Below, we can pass in an instance of a hatchback into the useCar method, because a hatchback is a Civic.

Screen Shot 2023-11-21 at 9.29.38 AM

Voila! The power of inheritance and polymorphism. A deep understanding of this concept is pivotal, but just one step in the vast journey of object-oriented programming.

Comments

topicTopics
academics study skills MCAT medical school admissions SAT expository writing college admissions English MD/PhD admissions strategy writing LSAT GMAT GRE physics chemistry math biology graduate admissions ACT academic advice interview prep law school admissions test anxiety language learning premed MBA admissions career advice personal statements homework help AP exams creative writing MD study schedules test prep Common Application computer science summer activities history philosophy mathematics organic chemistry secondary applications economics supplements research 1L PSAT admissions coaching grammar law psychology statistics & probability legal studies ESL CARS SSAT covid-19 dental admissions logic games reading comprehension engineering USMLE calculus PhD admissions Spanish mentorship parents Latin biochemistry case coaching verbal reasoning DAT English literature STEM excel medical school political science AMCAS French Linguistics MBA coursework Tutoring Approaches academic integrity chinese letters of recommendation Anki DO Social Advocacy admissions advice algebra astrophysics business classics diversity statement genetics geometry kinematics linear algebra mechanical engineering mental health presentations quantitative reasoning skills study abroad technical interviews time management work and activities 2L DMD IB exams ISEE MD/PhD programs Sentence Correction adjusting to college algorithms amino acids analysis essay art history artificial intelligence athletics business skills careers cell biology cold emails data science dental school finance first generation student functions gap year information sessions international students internships logic networking poetry resume revising science social sciences software engineering tech industry trigonometry writer's block 3L AAMC Academic Interest EMT FlexMed Fourier Series Greek Health Professional Shortage Area Italian Lagrange multipliers London MD vs PhD MMI Montessori National Health Service Corps Pythagorean Theorem Python Shakespeare Step 2 TMDSAS Taylor Series Truss Analysis Zoom acids and bases active learning architecture argumentative writing art art and design schools art portfolios bacteriology bibliographies biomedicine brain teaser campus visits cantonese capacitors capital markets central limit theorem centrifugal force chemical engineering chess chromatography class participation climate change clinical experience community service constitutional law consulting cover letters curriculum dementia demonstrated interest dimensional analysis distance learning econometrics electric engineering electricity and magnetism escape velocity evolution executive function freewriting genomics graphing harmonics health policy history of medicine history of science hybrid vehicles hydrophobic effect ideal gas law immunology induction infinite institutional actions integrated reasoning intermolecular forces intern investing investment banking lab reports linear maps mandarin chinese matrices mba medical physics meiosis microeconomics mitosis mnemonics music music theory nervous system neurology neuroscience object-oriented programming office hours operating systems