**Java之多态理解**
- Java 的多态是建立在继承与接口之上的,
- Java的继承跟接口给我们提供了安全向上转型。
**多态运用的原理**
1. 动态绑定(OOP的核心技术)
2. 继承与接口作支持
**使用多态时,应注意在哪些地方是不起作用的**
1. 构造器不能进行多态
2. private 方法不能应用与多态,因为 private 方法相当于 final方法,不能被重写
3. final 关键字修饰的方法或者类
4. static 关键字修饰方法
5. 变量不能应用于多态
6. 在构造器中应少使用多态,很难查找问题出在哪个位置
多态非常抽象,用到的技术点也很多,其中 对像的动态引用,动态绑定,转型...
在此写出一个Demo,便于理解
```
class Meal{
Meal(){
System.out.println("Meal()");
}
}
class Bread{
Bread(){
System.out.println("Bread()");
}
}
class Cheese{
Cheese(){
System.out.println("Cheese()");
}
}
class Lettuce{
Lettuce(){
System.out.println("Lettuce()");
}
}
class Lunch extends Meal{
Lunch(){
System.out.println("Lunch()");
}
}
class PortableLunch extends Lunch{
public PortableLunch() {
System.out.println("PortableLunch()");
}
}
public class Sandwich extends PortableLunch{
private Bread b = new Bread();
private Cheese c = new Cheese();
private Lettuce ll = new Lettuce();
public Sandwich(){
System.out.println("Sandwich()");
}
public static void main(String[] args) {
new Sandwich();
}
}
```
在此给出程序的运行结果
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
Sandwich()