java多态和接口

多态
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();
    }

}









  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值