Java中继承对Interface的影响
今天在总结Java和OC中Interface/Implement/Protocol的时候顺便逼逼了面向对象语言的吹逼就想到了一些特性还没有确定,就测试了一下
//接口1
public interface FirstInterface {
void doFirstMethod();
}
//接口2继承于接口1
public interface SecondInterface extends FirstInterface {
void doSecondInterface();
}
//实现接口2的Class会要求实现接口1
public class FatherImpl implements SecondInterface {
@Override
public void doFirstMethod() {
System.out.print("Do First Method In FirstImpl");
}
@Override
public void doSecondInterface() {
System.out.print("Do Second Method In FirstImpl");
}
}
//继承了实现接口2的Class不要求实现接口2
//但是可以对父类的接口函数进行重载
public class ChildImpl extends FatherImpl {
@Override
public void doFirstMethod() {
System.out.print("Do First Method In ChildImpl");
}
@Override
public void doSecondInterface() {
System.out.print("Do Second Method In ChildImpl");
}
}
OC中继承对Protocol的影响
OC中不管协议在父类中是私有的还是公开的Protocol协议的公开和非公开实现,在子类中都可以对其进行重载,只不过一个有代码提示一个没有代码提示罢了,[Child selector]向子类发消息,如果子类有同名函数,就会执行子类的,这是OC的消息机制决定的,可以看MethodSwizzling方法hook函数
//FatherObject.h
#import <Foundation/Foundation.h>
//协议1
@protocol FatherFirstDeletgate <NSObject>
@required
- (void)doFirstMethod;
@end
//协议2本身遵守协议1
@protocol FatherSecondDelegate <NSObject,FatherFirstDeletgate>
@required
- (void)doSecondMthod;
@end
//父类
@interface FatherObject : NSObject
@property (nonatomic, weak) id<FatherSecondDelegate> delegate;
@end
//FatherObject.m
#import "FatherObject.h"
//父类要求遵守协议2
@interface FatherObject () <FatherSecondDelegate>
@end
//父类要求实现协议1和协议2中所有required的方法
@implementation FatherObject
- (void)doFirstMethod {
NSLog(@"Do First Method In Father");
}
- (void)doSecondMthod {
NSLog(@"Do Second Method In Father");
}
@end
//ChildObject.h
#import "FatherObject.h"
//子类继承于父类
@interface ChildObject : FatherObject
@end
//ChildObject.m
#import "ChildObject.h"
//子类不要求实现协议1和协议2
@implementation ChildObject
@end