Welcome!

Java Authors: Yeshim Deniz, Trevor Parsons, Pat Romanski, Elizabeth White, Liz McMillan

Related Topics: Java

Java: Article

Are You Using Abstract Classes, Polymorphism, and Interfaces?

Are You Using Abstract Classes, Polymorphism, and Interfaces?

If the answer is no, at a minimum your project needs a code review.

Let's work on the following assignment: a company has employees and consultants. Design classes with and without the use of inheritance to represent the people who work for this company. The classes should have the following methods:

 

  • changeAddress
  • promote
  • giveDayOff
  • raiseSalary

Promotion means giving one day off and raising the salary by a specified percentage. For employees, the method raiseSalary should raise the yearly salary and, for consultants, it should increase their hourly rate.

Abstract Classes
A class is called abstract if it has at least one abstract (not implemented) method. The keyword abstract has to be placed in the definition of the method(s) and the class itself. For example, the class in Listing 1 has three concrete methods and one abstract. (The link to the source code is available below the article)

Abstract classes cannot be instantiated, but they allow you to create superclasses that implement some of the functionality, while leaving one or more methods to be implemented in subclasses.

The class Person can contain dozens of concrete methods that are the same for every person, such as changeAddress and giveDayOff, but since the process of raising a salary is different for employees and consultants, the method raiseSalary should remain abstract. Please note that even though this method is abstract, it could be called in an abstract class because by the time the concrete class is instantiated, the method will be already implemented. Since we have two types of workers, let's create subclasses Employee and Consultant and implement the method raiseSalary based on different rules (see Listings 2 and 3).

The designer of the class Person may not know the specifics of the raising salary process, but this does not stop him or her from calling the method raiseSalary. Programmers writing subclasses are forced to write an implementation of this method according to its signature declared in the abstract class. If they declare a method raiseSalary with a different argument list, this will be considered method overloading and the subclass will remain abstract. The class Promoter in Listing 4 shows how to use the classes Employee and Consultant for promoting workers.

Polymorphism
A programming language could be considered object-oriented if it supports inheritance, encapsulation, and polymorphism. The first two notions can be easily defined:

  • Inheritance lets you design a class by deriving it from an existing one. This feature allows you to reuse existing code without doing copy and paste. Java provides the keyword extends for declaring inheritance.
  • Encapsulation is the ability to hide and protect data. Java has access-level qualifiers such as public, private, and protected to control who can access class variables and methods. There is also so-called package-level protection, which is automatically engaged if you don't use any of the access-level keywords.
  • Polymorphism, though, is easier to understand through an example. Let's look at the classes Person, Employee, and Consultant from a different angle. We'll populate a Vector, mixing up the instances of classes Employee and Consultant - in real life this information usually comes from a database. For example, a program could get the person's work status from the database and instantiate an appropriate concrete class. The class Promoter (see Listing 4) will give an additional vacation day and increase the salary or hourly rate of every worker by 5%.

Please note that even though we cast every object from the collection workers to the ancestor's type Person in line 17, Listing 4, the variable pers can hold references to its descendent objects. The actual object type will be evaluated during runtime only. This feature of object-oriented languages is called runtime or late binding.

The output of the class Promoter will look as follows:

Class Person: Promoting a worker...
Class Person: Adding a day off
Class Employee:Increasing salary by 5%
Class Person: Promoting a worker...
Class Person: Adding a day off
Class Consultant: Increasing hourly rate by 5%
Class Person: Promoting a worker...
Class Person: Adding a day off
Class Employee:Increasing salary by 5%
Class Person: Promoting a worker...
Class Person: Adding a day off
Class Employee:Increasing salary by 5%

Both classes Employee and Consultant are inherited from the same base class Person. Instead of having different methods for increasing the worker's compensation based on its type, we give a polymorphic behavior to the method raiseSalary, which applies different business logic depending on the type of object from the collection. Even though it looks as if we're calling the same method promote, this is not the case. Since the actual object type is evaluated during runtime, the salary is raised properly according to this particular object's implementation of the method raiseSalary. This is polymorphism in action.

The while loop in the class Promoter will remain the same even if we add some other types of workers inherited from the class Person. For example, to add a new category of worker - a foreign contractor - we'll have to create a class Foreign- Contractor derived from the class Person and implement the method raiseSalary there. The class Promoter will keep casting all these objects to the type Person during runtime and call the method raiseSalary of the proper object.

Polymorphism allows you to avoid using switch or if statements with the expensive operator instanceof. Listing 5 shows an ugly alternative to our while loop from the class Promoter that assumes there is no abstract method raiseSalary, but we have separate promote methods in each subclass of the Person. This code would work slower than the polymorphic version from the class Promoter, and the if statement would have to be modified every time a new type of worker is added.

Interfaces
A similar functionality could be implemented using Java interfaces. We'll keep working with a modified version of the ancestor class Person because it has such useful methods as changeAddress and giveDayOff. But this class doesn't have to be abstract anymore because the method raiseSalary will be moved to a Java interface. The method promote won't be needed; we'd rather make the method giveDayOff available to descendants of the class Person by changing the private access level to protected (see line 8 in Listing 6).

Here's the "interface way" to ensure that each person in the firm receives the proper salary raise despite the differences in payroll calculation.

Let's define an interface Payable in Listing 7. More than one class can implement this interface (see Listing 8). When the class Consultant declares that it implements interface Payable, it promises to write implementations for all methods declared in this interface - in our case it's just one method raiseSalary. Why is it so important that the class will "keep the promise" and implement all the interface's methods? In many cases interface is a description of some behavior. In our case behavior Payable means the existence of the method boolean raiseSalary(int percent). If any other class knows that Employee implements Payable, it can safely call any method declared in the Payable interface (see the interface example in Listing 9).

Let's forget for a moment about employees and consultants and switch to the Java AWT listeners and events. When a class declares that it implements the interface java.awt.Action- Listener, a JVM will call the method actionPerformed on this class whenever the user clicks on the window's button, and in some other cases as well. Try to imagine what would happen if you forgot to include the method actionPerformed in your class. The good news is that your class won't even compile if not all methods declared in the interface were implemented. The java.awt.WindowListener interface declares seven methods, and even if you are interested only in the windowClosing one, you must include six additional empty-bodied methods to compile the class (window adapters simplify this process, but they are beyond the scope of this article).

While both abstract classes and interfaces can ensure that a concrete class will have all required methods, abstract classes can also contain implemented methods, but interfaces can't.

Beside method declarations, interfaces can contain final static variables. For example, let's say we have multiple bonus-level codes used in several classes during the calculation of new salaries. Instead of redefining these constants in every class that needs them, we can create the interface shown in Listing 10.

Now a small change in the class declaration will allow us to use these bonus levels as if they were declared in the class Employee:

public class Employee
implements Payable, Bonus {
...
if (empLevel==JUNIOR_LVL){
//apply the rules for juniors
}
}

public class Consultant
implements Payable, Bonus {
...
}

Java does not allow multiple inheritance, which means a class can't have two independent ancestors, but you can use interfaces as a workaround. As you've seen in the example above, a class can implement multiple interfaces; it just needs to implement all methods declared in all interfaces. If your window needs to process button clicks and window closing events, you can declare a class as follows:

 

class MyWindow implements ActionListener, WindowListener{S}

During evolution, an Employee can obtain multiple behaviors, for example

 

class Employee extends Person
implements Payable, Transferable,
Sueable, Bonus {...}

Consultants such as myself are usually more primitive creatures and can be defined as follows:

class Consultant extends Person
implements Payable, Sueable {...}

But if a program such as Promoter is interested only in Payable functions, it can cast the object only to those interfaces it intends to use, for example:

 

Employee emp = new Employee();
Consultant con = new Consultant();
Payable person1 = (Payable) emp;
Payable person2 = (Payable) con;

Now we're ready to write a second version of the class Promoter that will use the classes Employee and Consultant defined in Listings 8 and 11.

The output of this program will look similar to the output of the class Promoter from Listing 4:

Class Employee:Increasing salary by 5%
Class Consultant: Increasing hourly rate by 5%
Class Employee:Increasing salary by 5%
Class Employee:Increasing salary by 5%

Line 18 of Listing 9 may look a little confusing: How can we call a concrete method raiseSalary on a variable of an interface type? Actually we call a method on a concrete instance of the Employee or a Consultant, but by casting this instance to the type Payable we are just letting the JVM know that we're only interested in the methods that were declared in this particular interface.

Java Technical Interviews
During the technical interviews, probably the most frequently asked question is, "What's the difference between Java abstract classes and interfaces?" While interviewing Java programmers, I also found out that only half of the job applicants could properly complete the assignment described at the beginning of this article.

During the job interview your answers should be clear and short; you won't even have a chance to use all the material presented here. Here's one version of the answer to our problem.

If two classes have lots of common functionality, but some methods should be implemented differently, you could create a common abstract ancestor Person and two subclasses Employee and Consultant. The method raiseSalary must be declared abstract in the class Person while other methods should be concrete. This way we ensure that the subclasses do have the method named raiseSalary with a known signature, so we could use it in the ancestor without knowing its implementation. Java interfaces should also be considered in cases when the same method must be implemented in multiple classes - in this case we do not need to use abstract ancestors. Actually, interfaces could be your only option if a class already has an ancestor that can not be changed.

One good interview technique is to impress the interviewer by elaborating on a related topic. Discussion of abstract classes and interfaces gives you a good opportunity to show your understanding of polymorphism.

Summary
Use of abstract classes, interfaces, and polymorphism improves the design of any project by making it more readable and easily extensible. This also makes your code more compact and elegant.

More Stories By Yakov Fain

Yakov Fain is a co-founder of two software companies: Farata Systems and SuranceBay. He authored several technical books and lots of articles on software development. Yakov is Java Champion (https://java-champions.java.net). He leads leads Princeton Java Users Group. Two of Yakov's books will go in print this year: "Enterprise Web Development" (O'Reilly) and "Java For Kids" (No Starch Press).

Comments (4) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
sherali Inamdar 12/14/07 05:04:48 AM EST

Hi Dear Yakov Fain,
Even If a class Dont Have Abstract Method(i.e all methods may concrete), we can declare it as a Abstract Class. just appending the keyword

Taitelman mordechai 12/10/07 11:28:31 AM EST

Regarding your last paragraph: when to use Abstract class vs. Interface:
In terms of OOD the decision is more architectural:
Abstract class and interfaces are two ways to enforce an implementation in sub-classes.
However, I believe the main importance of Interfaces in Java is to overcome the multi-inheritance limitation.
The 2nd issue is agreed API between components. Two people should declare an interface if they intend to split up and re-join after several months. So what you should consider is: what is the probability this class would cross the boundaries of the component ?
Abstract class should be considered more inside the component. In many cases abstract classes are added in order to prevent circular dependencies between packages (in the same component). Furthermore, abstract class is your way to enforce some implementation details.
Beside that, in Java an interface is identical to (pure) abstract class.

punit pandey 09/04/03 11:00:08 AM EDT

It is a great article. good for newbies.

Steve Kasson 09/03/03 09:14:05 AM EDT

The source code is not available for this article. It references Listings 1 - 11, but I cannot find them anywhere.

Otherwise... excellent article.

-Steve

@ThingsExpo Stories
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
IoT is still a vague buzzword for many people. In his session at @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, discussed the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. He also discussed how IoT is perceived by investors and how venture capitalist access this space. Other topics discussed were barriers to success, what is new, what is old, and what the future may hold. Mike Kavis is Vice President & Principal Cloud Architect at Cloud Technology Pa...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world. The next @ThingsExpo will take place November 4-6, 2014, at the Santa Clara Convention Center, in Santa Clara, California. Since its launch in 2008, Cloud Expo TV commercials have been aired and CNBC, Fox News Network, and Bloomberg TV. Please enjoy our 2014 commercial.