【发布时间】:2015-05-19 13:59:16
【问题描述】:
据说封装是对数据和方法的封装,并隐藏此对象外部不需要的功能(方法和实例变量)
我的问题只是将变量设为私有,而公共是封装?还是做一个有抽象的类也是封装?
例如: 我有开关(电子开关)课在做开或关 为了制作一个 Switch 类,我使用了抽象 我使用抽象封装了 Switch 类,以便我可以映射 电机或灯泡或任何电动仪器
public class Switch {
private boolean isOff = true;
private ISwitchListener listener;
public Switch(ISwitchListener listener) {
this.listener = listener;
}
public void trigger() {
isOff = !isOff;
if(isOff) {
listener.off();
} else {
listener.on();
}
}
}
public class Bulb implements ISwitchListener {
@Override
public void on() {
// TODO Auto-generated method stub
System.out.println("bulb is glittering");
}
@Override
public void off() {
// TODO Auto-generated method stub
System.out.println("bulb is not glittering");
}
}
public interface ISwitchListener {
public void on();
public void off();
}
public class Executor {
public static void main(String[] args) {
// TODO Auto-generated method stub
Switch swt = new Switch(new Bulb());
swt.trigger();
}
}
如果我在这里不使用抽象,我会有下面这样的类
public class Switch {
private boolean isOff = true;
public void trigger() {
isOff = !isOff;
Bulb b =new Bulb();
if(isOff) {
b.off();
} else {
b.on();
}
}
}
当我想将电机映射到开关时,我需要将类更改为 bleow
public class Switch {
private boolean isOff = true;
public void trigger() {
isOff = !isOff;
Bulb b =new Bulb();
if(isOff) {
b.off();
} else {
b.on();
}
}
}
public class Motor {
public void on() {
// TODO Auto-generated method stub
System.out.println("Motor is rotating");
}
public void off() {
// TODO Auto-generated method stub
System.out.println("Motor is getting off to rotate");
}
}
【问题讨论】:
-
它隐藏了实现而不是功能,隐藏功能没有多大意义。
-
"将变量设为私有和公有" 变量不能两者兼有。 “用抽象做一个类”我不知道这是什么意思。
标签: java oop encapsulation abstraction