java如何使用实现向类添加函数
如何在下面的代码中使用setter
public class SignalRunnable implements Runnable {
private final int x;
private short[] s;
public SignalRunnable(int _x) {
this.x = _x;
}
public void setS(short[] _s) {
this.s = _s;
}
@Override
public void run() {
// DO STUFF here
}
}
我尝试了下面的方法来使用我的类,但遇到了一个无法解决的方法错误
// Create the runnable/task to repeat.
Runnable runnable = new SignalRunnable(x);
// Cannot resolve method error here.
runnable.setS(s);
# 1 楼答案
你应该记住Liskov Substitution Principle规定的一个非常重要的设计原则:
API(也就是说,可访问的,通常被称为
public
),可用于引用变量,由变量的类型决定和投影,而不是由实际对象的类型,变量存储引用。变量的类型是用什么声明的,而不是引用什么在下列情况下:
obj
只允许您访问在SuperType
中声明的成员(包括SuperType
隐式或显式从其超类型继承的任何内容)