Reputation: 899
Typically, a class implements an interface, and the class itself or its child class override the methods in the interface, such as:
Define an interface:
interface Interface {
void fun();
}
1.Parent class override the interface method, and child class direct inherit:
public class Parent implements Interface{
public void fun(){
}
}
public class Child extends Parent{
}
Or:
2.The parent class is defined as an abstract class and the child class override the methods in the interface:
public abstract class Parent implements Interface{
}
public class Child extends Parent{
public void fun(){
}
}
However, I also see a strange way to override the interface method:
3.The child class only implement interfaces, but override methods in the interface by the parent class:
public class Parent{
public void fun(){
}
}
public class Child extends Parent implements Interface{
}
The third way to override the interface method is very common in the android framework source code, for example:
public interface ViewParent {
//......
void requestLayout();
ViewParent getParent();
}
public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
//......
@CallSuper
public void requestLayout() {
//......
}
public final ViewParent getParent() {
return mParent;
}
}
public abstract class ViewGroup extends View implements ViewParent, ViewManager {
//......
}
The method requestLayout() and getParent() comes from ViewParent, and ViewGroup implements ViewParent, but why does the implementation of the method be done in the parent class View?
What is the reason for this design?
Upvotes: 3
Views: 2938
Reputation: 394156
Well, every View
has a parent View
, so the base View
class needs a getParent()
method and has a mParent
property.
However, View
doesn't implement ViewParent
, since not all views are parents of other views.
If View
was implementing some basic "ViewInterface", it would be possible to include getParent()
in that interface, but since it doesn't, getParent()
was included in the ViewParent
interface.
And since View
already implements that method, the ViewGroup
sub-class doesn't have to implement it.
Upvotes: 0