Choosing Between Contracts and Partial Blueprints, Explained

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

Choosing Between Contracts and Partial Blueprints

Data Structures and Algorithms · Chapter 3: Thinking in ObjectsSection 3.4 · lesson 10 of 8711 min · free with a free account

← How Child Types Borrow and Extend Behavior from Parent TypesNext lesson: Defining Data Behavior Without Implementation Details →

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

Choose between Java interfaces and abstract classes for a design.

  • Define an interface and implement it with every promised method
  • Write an abstract class with finished code and abstract methods for children to fill
  • Explain why a class extends one parent but may implement many interfaces
  • Choose an interface, an abstract class or both for a given design

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,563 words). Read along, or search it.

Opening Question

Wall Sockets and Unfinished Kitchens

Think about a wall socket. Its shape is a contract: any device with a matching plug can use it, a lamp, a charger, or a fan. Now think about a house plan where the walls and roof are built, but the kitchen is empty. That's a partial blueprint: much of the work is done, and whoever moves in finishes it. Java has one tool for each idea: an interface, and an abstract class. Picking the wrong one still compiles, but makes the design harder to change. So how do you choose?

Definition

Interfaces as Named Method Contracts

Picture a drawing program with circles, rectangles and photos. It needs to ask any of them to scale itself, and to describe itself in a sentence. An interface is a named list of methods that a type promises to provide. It says what can be asked, and nothing about how the work is done. A method in an interface has a name, inputs and a result type, but it ends in a semicolon instead of a body. Here's a contract for anything that can be resized. And a second contract, Describable, promises a one-sentence description.

Common Error

Signing Without Delivering

A type signs the contract by adding implements Scalable to its heading, then writing a real body for scale by, marked at override. Leave out even one promised method, and the compiler refuses. Here's a sticker that signs, then writes nothing. Sticker is not abstract, and does not override the abstract method scale by. Read it as: you signed, so you must deliver. The words, is not abstract, point to the other tool.

Key Benefit

Code That Depends Only on the Promise

What makes a contract valuable is that code can depend on the promise alone. A method that receives a Scalable doesn't need to know whether it holds a circle, a photo, or something invented next year. It only needs scale by to exist. So it works for every type that signs, now and later, without a single change. Unrelated types can be treated alike, because of what they can do, not what they are.

Definition

Abstract Classes as Partial Blueprints

An abstract class is a type that's deliberately left unfinished. It can hold stored values, constructors, and fully written methods, like any ordinary class. And it can declare abstract methods: a name and a result type, but no body, marked with the word abstract. Its children must fill those blanks. Here are the parts every shape shares. The name field and get name are finished, so every child gets them for free. Area is a blank, because a circle and a rectangle compute it differently, and the blueprint can't know which. Describe is finished, yet it uses the blank: it calls area, and trusts each child to have written it.

Compile Error

Abstract Classes Cannot Be Instantiated

Because a blueprint is incomplete, Java won't let you build an object from it. Shape is abstract, cannot be instantiated. A shape with no particular shape has no area, so such an object would be broken from the start, and the compiler stops it before anything runs. A concrete child that fills every blank can be built, and the blueprint's constructor still runs for it, through super.

Worked Example

Circle Extends Shape and Signs Scalable

Here's a concrete child. Circle extends the one blueprint, Shape, and also signs Scalable. Java writes both in one heading: the parent after extends, the contracts after implements. Its constructor passes the name up to the blueprint with super, Circle, then stores the radius. It fills the blank, area, with pi times radius squared. And it keeps the contract's promise, scale by, by multiplying the radius.

Key Rule

Only One Parent After Extends

The two tools differ sharply in how many a type may use. A type may extend exactly one parent, but implement as many interfaces as it needs. Here's what happens when an oval tries to inherit from both Shape and Circle. Brace expected. It isn't a missing brace in the usual sense. The compiler reads one name after extends, sees a comma, has no rule that allows more, and stops right at it.

Explanation

Why Java Allows a Single Parent

Why does Java insist on one parent? A parent passes down stored values and finished method bodies. If two parents each supplied a different version of the same method, or each stored a field with the same name, the child would have no clear answer to: which one do I use? An interface avoids the problem. It stores no per-object values and, in the form used here, supplies no method bodies, so signing many contracts never creates a conflict. Since Java 8, an interface may also carry a few ready-made methods, marked default, so old contracts can grow without breaking old code. For choosing between the tools, this table is the useful picture.

Quick Check

Which Class Must Write Play

Quick check. Playable promises play. Instrument is abstract, signs Playable, and adds its own blank, name. Drum extends Instrument, and writes name. Does Band compile, and if not, which class does javac complain about? Pause, and predict. It doesn't compile, and the error is about Drum. Drum is not abstract, and does not override the abstract method play. Instrument may leave play unwritten, because an abstract class is allowed to keep blanks. But Drum is concrete, so it must fill every blank it inherits, including the contract's promise.

Decision Guide

Questions That Pick the Tool

When a new design needs something shared, a few short questions pick the tool. First: must unrelated types offer this ability? A circle and a photograph can both be resizable, but they can't share a parent. Only an interface can join them. Second: do close relatives repeat the same fields, or the same finished code? Then an abstract class lets that code be written once. If nothing is repeated, an abstract class would have nothing to hold, so an interface is enough. And if a type already has a parent but needs one more ability, a second parent isn't allowed, but another contract is. Many children needing the same constructor setup also points to an abstract class, because interfaces have no constructors.

Combined Design

Using Both Tools Together

The choice isn't always either-or. Many designs use an interface for the promise, and an abstract class as a helpful starting point. Back to the drawing program. Every item must describe itself, and be enlarged, so those are two contracts: Scalable promises scale by, and Describable promises describe. Circles and rectangles also share a name and a sentence builder, so they share the Shape blueprint, which signs Describable and keeps that promise for all its children at once.

Worked Example

Rectangle Follows the Circle Pattern

Rectangle follows Circle's pattern exactly. It extends Shape, signs Scalable, and passes its name up. And it fills area with width times height, and scales both of its sides by the same factor.

Worked Example

A Photo That Signs Both Contracts

Photo has nothing in common with shapes except the two promises. It isn't a kind of shape, so it extends nothing, signs both contracts, and writes both methods itself. Scale by multiplies the width and height, rounding back to whole pixels. And describe builds its own sentence, because it can't use the one in Shape.

Demo

Enlarging Items Through Contracts Alone

Finally, a short program uses all three. Notice that the helper methods, enlarge and show, mention only the contracts. They never name a circle, a rectangle, or a photo. Run it. The first three lines come from show, which has no idea what it's given. For the circle, the sentence comes from Shape's finished describe, which reaches the circle's own area: three point one four. The photo skips the blueprint, and uses its own sentence. After enlarge doubles each item, the circle's radius is two, so its area is twelve point five seven: four times larger, because area grows with the square of the radius. The rectangle is four by six, and the photo is eight hundred by six hundred.

Extensibility

Adding Triangles and Stickers

Now think about growth. Add a triangle: it extends Shape, supplies area, and gets its name, get name and describe, for free. Add a sticker that has nothing to do with shapes: it signs Scalable, and nothing in enlarge has to change. Each new type touches as little existing code as possible.

Quick Check

Reports That Can Be Emailed

Quick check, a new design. Three kinds of report, sales, payroll and inventory, all store a title, and share the same code that prints a header. Only sales and payroll reports must also be emailable. Which pairing of tools fits? Pause, and decide. Report the parent, as an abstract class, and Emailable a contract. The three reports are close relatives repeating a field and finished code, so that part is written once, in Report. Emailable applies to only some of them, and a report can't have a second parent, so it's a contract that sales and payroll sign, while inventory leaves it out.

Common Mistakes

Misusing Interfaces and Abstract Classes

A few mistakes to avoid. Using an abstract class just to share a promise: if no field or code is shared, an interface is lighter, and leaves the type free to extend something else. Forcing unrelated types under one parent. Making Photo extend Shape just to reuse a sentence would give it a meaningless area. And trying to build an object from an interface or an abstract class. Only a finished, concrete type can be built with new.

Key Takeaways

Contracts, Blueprints or Both

To summarize. An interface is a contract: methods a type promises to offer, with no finished code to share. An abstract class is a partial blueprint: fields, constructors and finished methods, plus abstract methods every child must fill. A type extends exactly one parent, but may implement any number of interfaces. Choose an interface when unrelated types share an ability, and an abstract class when close relatives share code. Often, use both.

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 Choosing Between Contracts and Partial Blueprints

What is the difference between an interface and an abstract class in Java?
An interface is a contract listing methods a type promises to provide, with no per-object fields, while an abstract class is a partial blueprint that can hold fields, constructors and finished methods alongside abstract ones. A class can extend only one abstract class but implement many interfaces. Neither can be created directly with new; only a concrete type that fills every blank can be built.
When should you use an interface instead of an abstract class?
Use an interface when unrelated types need to share an ability, such as a Circle and a Photo that are both Scalable, or when a type already has a parent and needs one more ability. Use an abstract class when close relatives repeat the same fields or finished code, or need the same constructor setup. Many designs use both, as when an abstract Shape implements Describable.
Why can't a Java class extend two classes?
A parent passes down stored fields and finished method bodies, so two parents could supply different versions of the same method, or fields with the same name, leaving the child no clear choice. Java avoids that by allowing exactly one parent after extends. A class may still implement as many interfaces as it needs, as in class Circle extends Shape implements Scalable.
What happens if a class does not implement all the methods of an interface?
A concrete class must supply a body for every method its interfaces promise, or the compiler refuses it with an error saying the class is not abstract and does not override an abstract method. An abstract class may leave an interface method unwritten, but every concrete class below it must then have a body for that method, written itself or inherited from a class in between, along with any abstract methods the abstract class declares.

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 →