5 Steps to a 5 AP Computer Science A 2017 (2016)

STEP 4

Review the Knowledge You Need to Score High

CONCEPT 9

The abstract class and the interface

IN THIS CONCEPT

Summary: This concept contains two advanced features of the Java language: abstract classes and interfaces. These two concepts are similar in some respects and different in others. They are both used extensively in high-level software designs.

Key Ideas

   Abstract classes and interfaces are similar in that:

  • They both contain method(s) without implementation.
  • They cannot be instantiated.
  • They work well with polymorphism.
  • You can make reference variables that refer to them.

   Abstract classes and interfaces are different in that:

  • An abstract class may contain instance variables.
  • An abstract class may contain methods that do provide implementation.
  • An abstract class must beextended by another class to complete the implementation.
  • An interface cannot contain instance variables.
  • An interface cannot contain methods that provide implementation.
  • An interface must beimplemented by another class to complete the implementation.

The abstract class

Definition of an abstract class

I had a high school coach who told his athletes what to do at practice during the week. However, on the weekends, he told us to work out but he didn’t tell us what kind of workout to do. So, how we worked out varied from person to person. Some kids played basketball; some worked out in the gym; others played video games. He told us that we had to work out but didn’t tell us how. My coach’s instructions were like an abstract method in an abstract class.

An abstract classs is similar to the Java classes that we have learned about so far, but it is also different in several ways. An abstract class must have the keyword abstract in its class declaration. It does not contain any constructors but should contain abstract methods . Abstract methods are methods that have the keyword abstract in the method declaration but do not contain any code . The fancy way of saying this is, “abstract methods do not contain any implementation.” Only the method declaration (followed by a semicolon) is stated; the method does not have a method body.

The fact that an abstract class does not contain any constructors poses a problem that we’ve never seen before. How can you possibly create an object from a class that doesn’t contain a constructor? The answer is, you can’t.

So What’s the Point of an abstract class ?

The answer lies in design. In the class hierarchy that we’ve studied so far, a subclass may override a superclass’s method if it wants to. In an abstract class, the subclass must override the methods that are labeled abstract . Typically, you choose to create an abstract class when you do not want to define a generic way to carry out a method, therefore leaving the job of implementing the method up to the child class. In the example above, the coach gave specific directions during the week and the athletes had to follow the directions. However, on the weekends, the coach gave very vague directions and the athletes got to carry out the directions any way they wanted to. An abstract class is used in software design when you want a parent class to contain some implemented methods but you also want it to contain some unimplemented methods. The abstract class requires any subclass of the abstract class to carry out the implementation of the abstract methods.

Declaring an abstract class

The keyword abstract must be included in the class declaration . Also, the methods that do not contain any implementation must have the keyword abstract in their declarations.

General Form for Declaring an abstract class with One Abstract Method

General Form for Declaring a Class That extends an abstract class

Who Has to Implement the Code for an abstract class?

Any class that extends an abstract class must make sure that all abstract methods are implemented.

However, it is possible for one abstract class to extend another abstract class. If this is the case, then the first subclass that is not an abstract class must make sure that all abstract methods are implemented.

Example

Suppose you have been hired by a video game company to design a game in which characters in the game move around from one place to another. Each character will extend a superclass called GameCharacter. Each character will move in its own individual way (some fly, some swim, some teleport, etc.); there is no generic way that they all move. The runner class will call a move method that will allow all of the characters to move.

Solution: Use an Abstract Class

Choose to make the GameCharacter superclass an abstract class that includes an abstract method called move . The move method does not have a method body, so there is no generic way for each character to move. When each subclass extends the abstract class, they will be forced to implement the move method. Then, you can make a collection of all of the characters and whenever you tell each character to move, they will move in the way that they know how. Polymorphism at work!

An abstract class Cannot Be Instantiated

You cannot make an object using an abstract class.

You can, however, make an object reference variable of the abstract class type.

Summary: abstract class

  • An abstract class
  • must include the keyword abstract in the class declaration
  • should include at least one method declaration that has the keyword abstract in its method signature and does not contain implementation
  • cannot be instantiated.
  • can include instance variables and implemented methods.
  • A subclass that extends the abstract class must implement the abstract methods from the abstract class (unless the subclass is also an abstract class!).
  • A subclass can only extend one abstract class.
  • An abstract class works really well for designs that include polymorphism.

The interface

Definition of an interface

The interface is a Java feature that is similar in some respects to the abstract class. The main difference between the two is that an interface only contains method declarations (without any implementation). The classes that contain the implementation for the interface use the keyword implements in their class declaration.

An interface is not a class but rather a reference type . Even though an interface is not a class, it can be a reference variable for an object of the class that implements it. You cannot make an object from an interface; however, you can make a reference variable of the interface type. Finally, unlike extending, a class can implement more than one interface .

An Interpretation of the English Word Interface

If you think of the use of the word interface in the English language, it may help to explain what a Java interface is. For example, a video service like Netflix streams movies to its users. Based on the device that the user is using, the interface for Netflix may look different. The Netflix screen on a laptop may look different than the Netflix screen on a smartphone, even though the movie is streaming to it in the same way! Each device has to have different code that takes in the video and displays it so the user can see it the way it should be seen on that particular device.

In this diagram, Netflix streams a movie and tells the devices that they have to figure out how to display it. The software in the devices must implement the code that actually displays the movie since the Netflix interface doesn’t supply it.

Declaring an interface

The interface declaration contains the keyword interface and does not contain the keyword class. The class that implements the interface is responsible for carrying out the code for the methods defined in the interface.

General Form for Declaring an interface and a Subclass That Implements It public interface nameOfInterface

Example

Suppose you have been hired by Netflix to write code for devices to play their streamed movies. You decide to use an interface design structure. The interface will have three methods: play, pause, and rewind. Since the hardware is different for different devices, each device has to have particular software that needs to be written specifically for the device. The important thing to remember is that Netflix simply streams the video and doesn’t tell the devices how to handle the play, pause, and rewind features. Each device must implement the methods for playing, pausing, and rewinding in the way that is specific to it. Design an interface and two classes that implement the interface, one for a smartphone and one for a laptop.

A Class Can implement More Than One interface

A class can only extend one other class; however, a class can implement as many interfaces as it wants to. It just has to implement the code for all the methods in every interface.

Example

Write three different interfaces and have one class implement all three.

Summary: interface

  • An interface
  • must include the keyword interface in its declaration
  • can only contain method declarations (and not the code)
  • cannot include any instance variables or constructors
  • cannot be instantiated (you cannot make an object from an interface)
  • cannot include any implemented methods
  • Any subclass that implements an interface must contain the code for the methods of the interface.
  • A class can implement more than one interface.
  • An interface works really well for designs that include polymorphism.

The List interface

The List interface is a popular interface in Java because it is used by many complex data structures. As the name suggests, it defines methods for handling items that are stored in some kind of list. Examples of classes that (ultimately) implement the List interface are ArrayList, LinkedList, and Vector. Each of these complex data structures has its own way of performing actions like getting, setting, adding, and removing items from a list. Therefore, the List interface defines these methods. However it does not include the code for carrying out the actions—that is the responsibility of the classes (or subclasses) that implement the interface.

The ArrayList class is the only class that implements the List interface that you are required to know on the AP Computer Science A Exam.

 Rapid Review

The abstract class

  • An abstract class is similar to the classes we’ve studied so far, with a few exceptions.
  • An abstract class is allowed to have unimplemented methods. These methods are declared abstract.
  • Abstract classes cannot be instantiated. They must be extended.
  • If a class extends an abstract class, then it must implement all the abstract methods from the abstract class.
  • If a subclass of an abstract class is also an abstract class, then the first subclass in the hierarchy that is not abstract must implement any remaining abstract methods that have not yet been implemented.
  • Abstract classes can have any number of methods or instance variables.
  • Technically, an abstract class does not have to have any abstract methods, but if this is the case, then you should just define the class without labeling it abstract.
  • You can create a reference variable of an abstract class type; however, you are not allowed to create objects from an abstract class.
  • You can make an array or an ArrayList of reference variables whose type is an abstract class.

The interface

  • An interface contains only method declarations. None of the methods in an interface contain any code.
  • Interfaces cannot have any instance variables, constructors, or implemented methods.
  • An interface is a contract with the class that implements it. By using the keywordimplements , the class signs this contract; the class is obligated to implement every method that is defined in the interface.
  • A class can implement more than one interface. If a class implements more than one interface, it must contain the implementation for the methods from all of the interfaces.
  • You can create a reference variable of an interface type; however, you are not allowed to create new objects from an interface.
  • A class that implements an interface can be instantiated.
  • You can make an array or an ArrayList of reference variables whose type is an interface.

 Review Questions

Basic Level

  1. Consider the following declarations.

Which of the following is a valid class declaration?

(A)   public class TryThis extends Iface1

(B)   public class TryThis implements Abs1

(C)   public class TryThis extends Abs1, Abs2

(D)   public class TryThis extends Iface1 implements Abs1, Abs2

(E)   public class TryThis extends Abs1 implements Iface1, Iface2

  1. Consider the following interface and classes.

Which of the following is true of WeddingDecorator and KidsPartyDecorator ?

(A)   They have identical copies of the three methods defined in the Decorator interface.

(B)   They have exactly three methods, as defined in the Decorator interface.

(C)   They may have multiple methods, which may or may not include the three methods defined in the Decorator interface.

(D)   They may have multiple methods, but the three methods defined in the Decorator interface must be among them.

(E)   There is no way to tell anything about their implementation from the information given.

Advanced Level

Questions 3–4 refer to the following classes.

  1. Which of the following is true of the class hierarchy?

(A)   Alpha as written could be defined as an interface, and Beta and Gamma could implement the interface with the same results.

(B)   Alpha contains an abstract method that Beta and Gamma must implement, but they may implement them in different ways.

(C)   Alpha contains an abstract method that Beta and Gamma must implement in exactly the same way.

(D)   Alpha is the parent of Beta and Beta is the parent of Gamma .

(E)   These classes will not compile. They are written incorrectly.

  1. Consider the following code segment in the main method of another class.

What is printed as a result of executing the code segment?

(A)   value: 2 num: 5

num: 6 value: 3

(B)   value: 2 num: 5

value: 3 num: 6

(C)   value: 2 num: 5

value: 4 num: 6

(D)   value: 2 num: 5

num: 6 value: 4

(E)   value: 2 num: 5

value: 2 num: 5

  1. Consider the following interface.

Which of these classes correctly implements the interface?

III.   

(A)   I only

(B)   II only

(C)   III only

(D)   I and II only

(E)   II and III only

  1. Free-Response Practice: Music Venue

A certain band plays at several venues throughout the year. Some venues are stadiums and some are clubs. When the band plays at a club, the ticket prices are all the same. When the band plays at a stadium, there are premium seats and general seats, each with a different price. The ticket prices for the stadium shows are decided ahead of time and cannot be changed: premium seats are $200 and general seats are $75. All venues have a name and maximum seating capacity. A club also has a genre.

Consider the following abstract class Venue and its subclasses, Stadium and Club .

  • Implement the abstract methodgetRevenue for the Stadium class.
  • Implement the abstract methodgetRevenue for the Club class.

 Answers and Explanations

Bullets mark each step in the process of arriving at the correct solution.

  1. The answer is E.
  • Youextend an abstract class, and you can only extend one.
  • Youimplement an interface, and you can implement as many as you want.
  1. The answer is D.
  • A class that implements an interface must implement every method defined in the interface, but how the class implements the method is entirely up to each individual class. WeddingPartyDecorator and KidsPartyDecorator must implement the three methods defined in the interface, but the methods may do entirely different things.
  • Classes that implement an interface may have as many other methods as they want in addition to the methods required by the interface.
  1. The answer is B.
  • Option A is incorrect. Alpha cannot be defined as an interface, because it contains a constructor and methods that have been implemented.
  • Option C is incorrect. When extending an abstract class, all methods must be implemented, but the details of the implementation are entirely up to each child class.
  • Option D is incorrect. Beta and Gamma are both subclasses (or children) of Alpha.
  • Option E is incorrect. The classes are written correctly.
  1. The answer is D.
  • bObject and gObject both have reference variables that are of the type Alpha. This will be OK with the compiler because all of the methods that they call exist in the Alpha class.
  • bObject is instantiated as an instance of the Beta class and gObject is instantiated as an instance of the Gamma class. At run-time, Java will treat them as Beta or Gamma objects, respectively.
  • Both the Beta class and the Gamma class define a display method, but those methods are different. When bObject.display() is executed, the Beta version of display is executed. When gObject.display() is executed, the Gamma version of display is executed.
  • When bObject is instantiated, it subtracts 3 from Alpha’s instance variable, but it is not a static variable. The different objects have their own copies of Alpha’s variables, just like different objects have their own copies of their own variables. When getValue() is called, it retrieves their individual copies of value. In the case of aObject, that’s 2, and in the case of gObject, that’s 4.
  1. The answer is C.
  • All three versions have methods with the right names, but:
  • Option I is incorrect. The methods that implement the interface must have the exact method declaration given in the interface. In this option, the return types are different.
  • Option II is incorrect. The methods that implement the interface must have the exact method declaration given in the interface. In this option, the getArea method takes a parameter.
  • Option III is correct. Like option II, option III has a getArea method that takes a parameter, but in option III, getArea is overloaded. The required version of getArea is also implemented.
  1. On the AP Exam, you are often asked to implement an interface or extend an abstract class like you were in this question. Check your answer against my version below. A few things to notice:
  • Final variables (constants) do not have to be declared with their value, but once a value has been assigned, it can never be changed. These variables do not have to be declared final, but doing so is good programming practice.
  • $ and _ are the only symbols that can be used in identifiers.
  • You don’t have to calculate the result and assign it to a variable, then return that variable. You can just return the calculation. This is especially common in methods that return a boolean. You will see return statements likereturn (x > 5 ); instead of if (x > 5) return true; else return false;

The implementation in the Stadium class:

The implementation in the Club class:







All materials on the site are licensed Creative Commons Attribution-Sharealike 3.0 Unported CC BY-SA 3.0 & GNU Free Documentation License (GFDL)

If you are the copyright holder of any material contained on our site and intend to remove it, please contact our site administrator for approval.

© 2016-2024 All site design rights belong to S.Y.A.