How Child Types Borrow and Extend Behavior from Parent Types

UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 3.3 Free with a free account

How Child Types Borrow and Extend Behavior from Parent Types

Data Structures and Algorithms · Chapter 3: Thinking in ObjectsSection 3.3 · lesson 9 of 8714 min · free with a free account

← Modeling Real-World Entities as Programmable ObjectsNext lesson: Choosing Between Contracts and Partial Blueprints →

Earn 3 college credits for Data Structures and AlgorithmsRecommended for credit by NCCRS · Computer Science 251 · self-paced · one payment, lifetime access

In this lesson

Reuse and extend parent behavior with inheritance, overriding and polymorphism.

  • Create a child class with extends and chain constructors with super
  • Override methods with the Override annotation and distinguish overriding from overloading
  • Explain declared versus actual types and how dynamic dispatch picks a method
  • Use upcasts, downcasts, instanceof and protected access safely

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,934 words). Read along, or search it.

Opening Question

Payroll Without Writing Things Three Times

Imagine a payroll program. Every employee has a name and a base salary, and can be asked for a pay amount. Managers also get a bonus. Engineers also get an on-call allowance. Without help, you'd write the name, the salary and the pay logic three times, and every later fix would have to be made in three places. So how do you write the shared part once, and let each special case add only what makes it special?

Key Idea

Is-a Versus Has-a

Writing the shared part once, and letting each child type add what's different, is called inheritance. The test for whether it fits is a sentence: a manager is an employee. If that sounds natural, the child can stand in anywhere its parent is expected. If it sounds odd, a car is an engine, the relationship is really has-a, and the car should simply hold an engine inside it. In Java, a type extends exactly one parent. And a type that names no parent quietly gets one anyway: Object, the type at the top of every chain.

Parent Class

The Employee Parent Class

Here's the parent, Employee, with private fields, a constructor, and three methods: get name, pay, and describe. Describe builds a sentence from the name, and from whatever pay returns. Remember that, because it matters later.

Child Class

Manager Extends Employee

And here's the child. Manager extends Employee. The keyword extends is the whole mechanism. What the child declares itself, the bonus field and get bonus, is added on top of everything it inherits.

Demo

Inherited Methods That Just Work

This program makes a manager, then asks for its name, its description, and its bonus. Run it: Asha, Asha earns five thousand point zero, and eight hundred point zero. Manager wrote no get name and no describe, yet both work. They were inherited.

What Is Inherited

Private Fields and Missing Constructors

A child carries every accessible member of its parent. Public and protected methods work with no extra code. One surprise: a manager object really does contain the parent's private base salary, because pay can't be computed without it. But the child's own code isn't allowed to name that field. And constructors are never inherited at all.

Constructor Chain

Calling Super First

Because constructors aren't inherited, a child constructor needs a way to set up the parent part of the object. That's super, with parentheses. It calls a constructor of the parent, and it must be the first statement. If you write no super call, Java inserts one for you, super with no arguments. The result is a chain: every constructor calls its parent's first, all the way up to Object. Here's a three-level chain. Only Boss calls super itself, and Worker's constructor has no super line at all. Run it: Person, then Worker, then Boss. The parent part is always built first.

Common Error

No Matching Parent Constructor

That rule has a consequence. Employee's only constructor needs a name and a salary. So when a child's constructor has no super call, the automatic super with no arguments has nothing to call. Constructor Employee cannot be applied to given types. Required: string, double. Found: no arguments. The fix is to take those two values, and pass them up with super, as the first line. A constructor may instead begin with this, which hands the work to another constructor of the same type. It can use this or super, never both.

Overriding

A Manager's Pay Includes the Bonus

Inheriting a method doesn't force you to keep its behavior. A child may supply its own version, with the same name and the same parameter list. That's overriding. A manager's pay should include the bonus, so Manager overrides pay. Super dot pay calls the parent's version, so the child extends the behavior instead of rewriting it. Run a short program: five thousand eight hundred. And describe, written in Employee, prints five thousand eight hundred too. Inside an inherited method, a call to pay still reaches the child's override.

Annotation

Override Catches a Misspelled Name

The at override line is a promise to the compiler: this method replaces one from a parent. It changes nothing at run time, but it turns silent mistakes into errors. Here the name is mistyped, with a capital P. Method does not override or implement a method from a supertype. Without the annotation, capital P pay would compile happily as a brand-new method, and pay would quietly keep its old behavior. So write at override on every override.

Override Rules

Four Rules for a Valid Override

A valid override follows four rules. Same name and parameter types: pay with an int parameter is a different method. The return type is the same, or a more specific child type. Access is the same or wider, never narrower. A package-level close method can't replace a public one, and the compiler says it's attempting to assign weaker access privileges. And private, static and final methods can't be overridden: private ones are invisible to the child, static ones are hidden, not overridden, and final ones are locked.

Comparison

Overloading Versus Overriding

Overriding and overloading sound alike, but they solve different problems. Overloading means several methods share a name, with different parameter lists. And the choice is made at different moments. An overloaded call is settled by the compiler, before the program runs, using only the declared types of the arguments. Both variables here point to a manager. But e is declared as Employee, so the compiler picks show, Employee. M picks show, Manager. And the very same object still answers e dot pay with the manager's five thousand eight hundred, because overriding is decided later, at run time.

Key Rule

Compiler Picks Overloads, Runtime Picks Overrides

Keep the two stages apart, and many puzzles disappear. Overloads differ in their parameters, and the compiler picks one from declared types. Overrides have identical parameters, and the running program picks one from the actual object. Only overrides are checked by at override.

Common Trap

An Equals That Overloads by Mistake

A famous trap: overloading when you meant to override. The equals method inherited from Object takes an Object. Writing equals that takes a Box doesn't override it. It adds a second method beside it. These two calls compare the same pair of boxes, yet the answers differ: true, then false. With the argument declared as Box, the new overload is chosen. Declared as Object, only the inherited identity check applies. Anything in Java that calls equals without knowing about boxes uses the inherited version. Adding at override would have stopped this program from compiling, and exposed the mistake at once.

Quick Check

Greet With an Object Holding Text

Quick check. Two greet methods: one takes an Object, one takes a String. X is declared as Object, but holds the text hi. What does the program print? Pause, and predict. It prints, object string. Overloads are chosen by the compiler, from declared types. X is declared Object, so greet of x calls the Object version, even though it holds a string. The literal hi is declared String, so the second call picks the String version.

Polymorphism

Declared Type and Actual Type

Now the heart of object-oriented design. A variable whose type is a parent may point to an object of any child type, so every variable has two types. The declared type is written in the source, and never changes. The actual type is that of the object made by new, fixed when it's built. The declared type decides what you may call. The actual type decides which version runs. Running different code depending on the object is polymorphism, and picking the version at the moment of the call is dynamic dispatch.

Second Child

Engineer Adds an On-Call Allowance

Here's the second child, Engineer. It overrides pay to add three hundred, and adds a method of its own, review, that managers and plain employees don't have.

Payoff

One Print Method for Every Employee

The payoff is code written once, for the parent, that works for every child, present and future. Payroll's print method knows nothing about managers or engineers. It receives an employee, and asks it to describe itself. Run it, and each object answers in its own way: four thousand, five thousand eight hundred, and six thousand three hundred. If a director type is added next year, Payroll doesn't change at all.

Compile Error

Declared Type Limits the Calls

The declared type's job is easy to see. An engineer object does have a review method, but a variable declared Employee may only use what Employee promises. Cannot find symbol: method review, location, variable e of type Employee. The compiler looked only at the declared type.

Casting

Upcasts, Downcasts and Failed Casts

Moving a reference up the hierarchy, child to parent, is always safe, and needs no syntax. That's an upcast. Moving down is different. An employee reference might hold any kind of employee, so you write the target type in parentheses, a downcast, to say: I take responsibility. When the object really is an engineer, the downcast works, and review is available again: Mei reviews code. But the next cast compiles, and then stops the running program. Class cast exception: class Engineer cannot be cast to class Manager. The object is an engineer, and an engineer is not a manager.

Compile Versus Runtime

Casting Between Sibling Types

Between unrelated types, the compiler refuses outright. Manager and Engineer are siblings, and no object could ever be both, so this cast is incompatible types. Related, but the wrong object: a run-time failure. Unrelated: a compile error. Two different failures, at two different stages.

Safe Casting

Checking With Instanceof First

The operator instanceof asks the question before you risk the cast. It's true when the object is of that type or any child of it, and false for null. Since Java 16, it can also give the checked reference a name in the same step, so g is ready to use inside the if. Run it: true, false, false, and Mei reviews code. If you find yourself checking instanceof for many child types in a row, the design is fighting polymorphism. Put the different behavior in an override instead.

Access Level

Protected Members for Child Types

Inheritance adds a middle access level. A protected member is visible to child types, and to code in the same package, but hidden from everyone else. Intern reads base salary directly, because it's protected. Run it: eleven fifty. Make the field private, and the child is shut out: base salary has private access in Staffer. Protected is a door, not a default. Prefer private fields, with protected or public methods, and open the door only when a child truly needs it.

Root Class

Methods Every Object Inherits

Every type has a parent: write no extends, and Java supplies extends Object. So every object inherits Object's methods, and three matter every day. To string gives the type name, an at sign, and a number. Equals is true only for the very same object. And hash code gives a number from the object's identity. Point overrides nothing. Tagged overrides all three, field by field, and its equals takes an Object, exactly as the parent's does, using instanceof before it reads the other value. Run it. Two points with the same values aren't equal. Tagged prints readably, its two objects are equal, and their hash codes match. Override hash code whenever you override equals: equal objects must give the same number.

Quick Check

A Premium Fee Dispatched at Runtime

Quick check. An account's fee is two. Bill, written in Account, builds a line from fee. Premium overrides fee to triple the parent's. A variable declared Account holds a premium account. What does bill print? Pause, and predict. It prints, fee six point zero. Bill is inherited, but its call to fee is dispatched on the actual object, a premium account, so the override runs: two, times three. The declared type, Account, only decided that bill could be called at all. It compiles, because Account does have a bill method.

Key Takeaways

Extends, Super, Overrides and Casts

To summarize. A child extends one parent, inherits its accessible members, and calls a parent constructor first, with super. Override with at override, and extend the parent's version with super dot method. Overloads are chosen by the compiler, overrides by the running object. The declared type decides what you may call, and the actual type decides which version runs. Guard every downcast with instanceof. And override equals and hash code together, taking an Object.

About Data Structures and Algorithms at UPI Study

Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms

Why take it here

Why students take Data Structures and Algorithms with UPI Study

How programs store and search dataData Structures and Algorithms teaches how to organize data and measure how fast code runs: arrays, linked lists, stacks, queues, trees, heaps, hash tables, sorting and graphs, all written in Java. It is a core course in computer science and software degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About How Child Types Borrow and Extend Behavior from Parent Types

What does super() do in a Java constructor?
super(...) calls a constructor of the parent class so the parent part of the object is built first, and it must be the first statement. If you write no super call, Java inserts super() with no arguments. That fails to compile when the parent has no constructor without parameters, such as an Employee that needs a name and a salary, so pass those values up explicitly.
What is the difference between method overloading and overriding in Java?
Overloading means several methods share a name but have different parameter lists, and the compiler picks one from the declared types of the arguments. Overriding means a child class supplies its own version of an inherited method with the same name and parameter types, and the running program picks the version from the actual object. Only overrides are checked by the @Override annotation.
What is dynamic dispatch in Java?
Dynamic dispatch means Java chooses which overridden method to run at the moment of the call, based on the object's actual type. If a variable declared as Employee holds a Manager object, the declared type decides which methods you may call, but calling pay() runs Manager's override. That lets code written for the parent, such as a payroll method, work unchanged for every child type.
Why does a downcast throw a ClassCastException in Java?
A downcast throws a ClassCastException when the object the reference actually holds is not of the target type: a cast between related types compiles, but the running program checks the real object. Casting an Employee reference that holds an Engineer to Manager throws a ClassCastException, because an engineer is not a manager. Casting between sibling types such as Manager and Engineer does not compile at all. Testing first with instanceof, as in if (e instanceof Engineer g), avoids the failure.

About the Data Structures and Algorithms course

How many college credits is Data Structures and Algorithms?
Data Structures and Algorithms (Computer Science 251) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Data Structures and Algorithms cost and what is included?
$250, paid once, with lifetime access: all 87 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Data Structures and Algorithms take?
It is self-paced with no deadlines. The 87 lessons total about 15 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Data Structures and Algorithms.

87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Data Structures and Algorithms
3 credits · NCCRS
Enroll →