人们说继承破坏了封装,我同意。他们说授权更好-尽管授权中的修饰语也可以是公共的/受保护的。
那么,由于超类的公共/受保护修饰符的“敲响”作用暴露于扩展当前子类的任何新类中,因此继承中断封装的真正原因是吗?
参考以下链接:
http://www.javaworld.com/javaworld/jw-11-1998/jw-11-techniques.html?page=2
代码重用的组合方法提供了比继承更强的封装,因为对后端类的更改不需要破坏任何仅依赖于前端类的代码.例如, 更改前一个示例中Fruit的peel()方法的返回类型不会强制更改Apple的界面,因此无需破坏Example2的代码.
当然如果你改变返回类型peel()(见下面的代码),这意味着getPeelCount()将无法再返回int?你不是必须改变界面,否则会得到编译器错误?
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
return fruit.peel();
}
}
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
Run Code Online (Sandbox Code Playgroud) 我在头文件和源文件之间分配了以下代码.在函数插入中,它表示AllBridges向量未初始化(它甚至似乎都没有识别它?)并且nextBridge没有赋值 - 除了我以为我在构造函数中做了什么?
#include <vector>
using namespace std;
class Bridge
{
public:
Bridge(int);
void insert(Bridge);
private:
int nextBridge;
vector<Bridge> AllBridges;
};
#include "StdAfx.h"
#include "Bridge.h"
using namespace std;
Bridge::Bridge(int size){
AllBridges.reserve(size);
nextBridge= 0;
}
void insert(Bridge AddBridge){
AllBridges[nextBridge] = AddBridge;
}
Run Code Online (Sandbox Code Playgroud)