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 medical school admissions MCAT SAT college admissions expository writing strategy English MD/PhD admissions writing LSAT physics GMAT GRE chemistry graduate admissions academic advice biology math law school admissions ACT interview prep language learning test anxiety personal statements premed career advice MBA admissions AP exams homework help test prep creative writing MD computer science mathematics study schedules Common Application summer activities history secondary applications philosophy research organic chemistry economics supplements 1L admissions coaching dental admissions grammar statistics & probability PSAT psychology law legal studies ESL reading comprehension CARS PhD admissions SSAT covid-19 logic games calculus engineering USMLE medical school mentorship Latin Spanish parents AMCAS admissions advice biochemistry case coaching verbal reasoning DAT English literature STEM excel genetics political science skills French Linguistics MBA coursework Tutoring Approaches academic integrity astrophysics chinese classics dental school gap year letters of recommendation mechanical engineering technical interviews units Anki DO Social Advocacy algebra art history artificial intelligence business careers cell biology data science diversity statement first generation student freewriting geometry graphing kinematics linear algebra mental health pre-dental presentations quantitative reasoning software engineering study abroad tech industry time management work and activities 2L AAMC DMD IB exams ISEE MD/PhD programs MMI Sentence Correction adjusting to college algorithms amino acids analysis essay argumentative writing athletics business skills cold emails executive function fellowships finance functions genomics information sessions international students internships logic networking office hours poetry proofs resume revising scholarships science social sciences trigonometry writer's block 3L Academic Interest ChatGPT EMT FlexMed Fourier Series Greek Health Professional Shortage Area Italian JD/MBA admissions Japanese Lagrange multipliers London MD vs PhD Montessori National Health Service Corps Pythagorean Theorem Python Shakespeare Step 2 TMDSAS Taylor Series Truss Analysis Zoom acids and bases active learning architecture art art and design schools art portfolios bacteriology bibliographies biomedicine brain teaser burnout campus visits cantonese capacitors capital markets central limit theorem centrifugal force chem/phys 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 embryology entropy escape velocity evolution extracurriculars fundraising 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 letter of continued interest linear maps