多态
1.什么是多态:
多态是指两个或多个属于不同类的对象对于同一个方法调用做出不同响应的方式
2..多态的语法结构 (大手牵小手:父类对象在前 实例化子类在后)
父类 对象名 = new 子类
eg:Question question = new Answer();
编译时(父类):Question
运行时(子类):Answer
2.怎么构成多态
- 要有继承
- 要有方法的重写
- 父类引用指向子类对象
3.多态的优势:
可替代性 可扩充性 灵活性 接口性 简化性
4.多态的代码:
创建一个父类Question
public class Question {
public void height() {
System.out.println("身高多少?");
}}
两个子类Answer1、Abswer2继承Question父类
public class Answer1 extends Question {
public void height() {
super.height();
System.out.println("190cm");
}
}
public class Answer2 extends Question {
public void height() {
super.height();
System.out.println("150cm");
}public static void main(String[] args) {
Question q = new Answer1();
q.height();
Question q1 = new Answer2();
q1.height();
}
}
接口
1.什么是接口
接口是一种特殊的抽象类,用interface来修饰,有一堆抽象方法,若要实现接口,必须要实现当中的所有方法。
2.为什么要使用接口
1.因为JAVA是单继承2.可以实现多个接口
3.使用接口的好处
接口可以精简程序,免除重复定义,提出设计规范
4.接口的关键字 implement
5.接口的代码
public interface Flyable {
public void fly();
}
public class Plane implements Flyable{
public void fly() {
System.out.println("飞机靠燃料飞行");
}
}
public class Birds implements Flyable{
public void fly() {
System.out.println("鸟靠挥动翅膀飞行");
}
public static void main(String[] args) {
Birds b = new Birds();
b.fly();
Plane p = new Plane();
p.fly();
}
}