Java Interfaces Flashcards
(15 cards)
How do interfaces help with inheritance?
Since multiple inheritance is not possible in Java, using interfaces can implement methods that aren’t hierarchially related.
Give the format of an interface called “Measurable” that returns a double named “getMeasure” with no parameters.
public interface Measurable {
double getMeasure();
}
How would class “This” implement the class “Measurable”?
public class This implements Measurable{}
Can you use interfaces like classes?
Yes you can pass interfaces that will take variables of type Measurable, which just takes instances of classes that implements Measurable.
What’s the difference between “abstract” and an interface?
Classes which extend an abstract are related through hierarchy, interfaces can be completely unrelated (also can implement multiple interfaces).
Using interfaces, how can I ensure a Node will be printable and comparable?
interface ListItem extends Comparable, Printable {}. Keep in mind interfaces are merely things that a class has to satisfy.
What is the protection of Interfaces?
All methods are public in interfaces, and must be public in the class which implements them as well.
Can you have instances of an interface?
No, interfaces are just a collection of methods, but polymorphism works for classes implementing an interface.
What are default methods?
Ways to update old interfaces which is a part of an interface that has code! The code can be redeclared, overriden, or left unchanged.
Whats the point of a default method?
To add a method to keep old code working (e.g. interface was created a while ago and lots of classes implement it)
What happens if a class implements 2 interfaces that contain the same method name and parameters?
cant happen, compile-time error (we can fix this by defining a new behaviour with the same type though)
What happens when a subclass has a parent and interface with the same method?
The subclass uses the superclass version, extends has priority
Can interfaces have static methods?
Yes, and referred to by the interface:
e.g. int1.staticMethod(…);
Can you have an interface inside another?
Yes, called nested interfaces
e.g.:
interface Printable {
void print();
interface Testable {
void test();
}}
How do I refer to a nested interface?
Specify the name of the outer interface, followed by a dot:
class Test implements Printable.Testable