今天我从朋友那里听到,封装不仅实现了信息隐藏,还实现了抽象.它是如何实现的?
public class employee {
private String name;
private int id;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的例子实现了封装,我允许类访问我的公共方法而不是私有成员,但这里的抽象在哪里?任何人都可以用一种清晰的方式向我解释抽象.
有两个不同的东西,信息隐藏和抽象.
信息隐藏使抽象成为可能,但它有所不同.例如,使用您的代码
public class employee {
private String name;
private int id;
public void setName(String name) {
this.name = name;
}
public String getName(){
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
该id字段实际上是隐藏的.这允许人们以与程序的其余部分分离的方式处理id.您的名称字段实际上也是隐藏的,因为您不直接访问名称字段,但代码中getName和setName.
一旦从其余代码隐藏数据结构,强制通过方法访问,就可以创建一些项目的可替换实现.例如,a employee是概念类型person,因此您可以像这样重写上面的内容:
public interface Person {
public abstract String getName();
}
public class Employee implements Person {
private String name;
private int id;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
现在你的代码可以处理Employee为Person.在重写了未明确处理Employees 的其余代码以处理Persons之后,您可以实现其他类型的Persons并利用现在Person任务的非Employee特定任务.
public Customer implements Person {
private String name;
private integer moneySpent;
public String getName() {
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
所以一个人搜索例程,只要它只对索引Person对象现在可以包括对Employees和Customers的搜索.这是因为处理Person对象的代码实际上是处理两者Employee和Customer对象共享的更高级别的抽象.
在抽象级别处理对象时,方法的名称在抽象中共享; 但是,执行的实际代码取决于对象的未提及的基础类型.换句话说,如果您询问一个人(恰好是一名员工),getName()那么它将响应该Employee.getName()功能,而一个人Customer将回复一个Customer.getName()功能.由于代码调用getName()是在Persons 上运行的,因此它不知道它将处理哪种类型的人,但行为的明显变化(基于每个对象选择正确的代码块)仍然会发生.这种现象被称为Polymorphisim,如果你是第一次触及这些概念,你会听到Polymorphisim作为一个经常使用的词.
多态行为的一个例子:
public interface Animal {
public abstract String makeSound();
}
public class Cow implements Animal {
public String makeSound() {
return "Moo Moo!";
}
}
public class Dog implements Animal {
public String makeSound() {
return "Ruff Ruff!";
}
}
public class Sheep implements Animal {
public String makeSound() {
return "Baa Baa!";
}
}
// this class demonstrates the polymorphic behavior
public class Farm {
public static void main(String[] args) {
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Cow());
animals.add(new Sheep());
animals.add(new Dog());
for (Animal animal : animals) {
// this is where the polymorphisim occurs
// each animal will make a different sound
// because the makeSound method is getting
// bound to different blocks of code based
// on the exact type of animal class hiding
// under the Animal abstraction.
System.out.println(animal.makeSound());
}
}
}
Run Code Online (Sandbox Code Playgroud)
预期产量:
Moo Moo!
Baa Baa!
Ruff Ruff!
Run Code Online (Sandbox Code Playgroud)
即使我们从未明确地更改类,我们也从未明确地更改过方法.它是抽象方法与正在改变的显式子类的绑定,这种情况只发生在支持多态性的系统中.