Abstract Classes and Interfaces Flashcards
What is an abstract class?
An abstract class is a class that cannot be used to create objects. It contains abstract methods.
How should constructors in abstract classes be created?
They should have the ‘protected’ modifier.
Can an abstract method be contained in a concrete class?
No. If there’s an abstract method, the class must be abstract.
What must the subclass do in regards to the abstract methods defined in the abstract superclass?
It must implement/override them all, or be defined as an abstract class itself.
Why would you want constructors in an abstract class, since you cannot instantiate the class?
Because they may be invoked by the constructors of concrete subclasses.
If GeometricObject is an abstract class, why can you do this?
GeometricObject[] objects = new GeometricObject[10];
Because you are not creating objects, you are creating 10 GeometricObject references inside the array. You can do that for the same reason you can do: GeometricObject obj = new Circle();
What is an Interface?
An interface is a class-like construct that contains only constants and abstract methods. It’s intent is to specify common behavior for objects of related classes or unrelated classes.
Where is the compareTo method defined?
It’s defined in the Comparable interface, and in all classes that implement the comparable interface.
What is the difference between abstract classes and interfaces in regards to variables?
Abstract classes has no restrictions in regards to variables, but interfaces can only have ‘public static final’ variables.
What is the difference between abstract classes and interfaces in regards to constructors?
An abstract class cannot be instantiated using the new operator, but subclasses can invoke the constructors through their own constructors using the super keyword. Interfaces have no constructors.
What is the difference between abstract classes and interfaces in regards to methods.
Abstract classes have no method restrictions. They may have abstract methods and concrete methods.
Interfaces can only have public abstract non-static methods.
What is the difference between abstract classes and interfaces in regards to inheritance?
Only single inheritance is allowed for abstract classes (a class may only extend one single class), but multiple inheritance is allowed for interfaces (a class may implement several interfaces).
How is an abstract class defined? What is the syntax?
An abstract class has the keyword 'abstract' in the header, like this: modifier abstract class className.
How is an interface defined? What is the syntax?
An interface has the keyword ‘interface’ in the header, like this:
modifier interface interfaceName.
How does a class make use of an interface?
By using the keyword 'implements' in the header, like this: class className implements interfaceName.