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 college admissions expository writing English MD/PhD admissions strategy writing LSAT GMAT physics GRE chemistry biology math graduate admissions academic advice ACT interview prep law school admissions test anxiety language learning career advice premed MBA admissions personal statements homework help AP exams creative writing MD study schedules test prep computer science Common Application summer activities mathematics history philosophy organic chemistry secondary applications economics supplements research 1L PSAT admissions coaching grammar law psychology statistics & probability legal studies ESL dental admissions CARS SSAT covid-19 logic games reading comprehension engineering USMLE calculus mentorship PhD admissions Spanish parents Latin biochemistry case coaching verbal reasoning DAT English literature STEM excel medical school political science skills AMCAS French Linguistics MBA coursework Tutoring Approaches academic integrity admissions advice astrophysics chinese gap year genetics letters of recommendation mechanical engineering Anki DO Social Advocacy algebra art history artificial intelligence business careers cell biology classics dental school diversity statement geometry kinematics linear algebra mental health presentations quantitative reasoning study abroad tech industry 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 athletics business skills cold emails data science finance first generation student functions graphing information sessions international students internships logic networking poetry proofs resume revising science social sciences software engineering trigonometry units 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 fellowships freewriting genomics 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

Related Content