JAVA小白的入门笔记—多态和接口

多态

一.定义:
多态是指两个或多个属于不同类的对象对于同一个方法调用做出不同响应的方式
多态是存在于编译时和运行时的一种状态

二.多态的语法结构
大手牵小手
父类 对象名 = new 子类
eg:Question question = new Answer();
编译时(父类):Question
运行时(子类):Answer

优势:1可替换性 2 可扩充性 3 灵活性 4 简化性
产生多态的条件
1.要有继承
2.要有方法的重写
3.父类应用指向子类对象

接口

一.什么是接口
(概念)是一种规范,不需要关心通过这个接口可以完成什么功能。
接口是一种特殊的抽象类,用interface来修饰,有一堆抽象方法,若要实现接口,必须要实现当中的所有方法。

*抽象类是A,接口是具备某种能力

二.为什么使用接口
1.应为JAVA是单继承
2.可以实现多个接口

为什么要使用接口:
接口可以精简程序,免除重复定义,提出设计规范。

下面附上一段小白写的多态的代码
首先我们要创建三个子类
猫类

package com.www.lenovo.demo;

public class Cat extends Animal{


    public void eat() {
        super.eat();
        System.out.println("小猫会睡觉");
    }
    public void run() {
        super.run();
        System.out.println("能抱会喝水");
    }
    public void cry() {
        super.cry();
        System.out.println("小猫喵喵喵");
    }
}

狗类

package com.www.lenovo.demo;

public class Dog extends Animal{
    public void eat(){
        super.eat();
        System.out.println("小狗和人玩");
    }
    public void run() {
        super.run();
        System.out.println("也会游泳");
    }
    public void cry() {
        super.cry();
        System.out.println("小狗汪汪汪");
    }



}

猪类

package com.www.lenovo.demo;

public class Pig extends Animal {
    public void eat() {
        super.eat();
        System.out.println("猪只会吃饭睡觉");      
    }
    public void run() {
        super.run();
        System.out.println("但是及其慢");
    }
    public void cry() {
        super.cry();
        System.out.println("佩奇 哼哼哼·");
    }
}

之后我们创建一个Animal父类,子类要继承

package com.www.lenovo.demo;

public class Animal   {
    public void eat( ) {

        System.out.print("它是:");
    }
    public void run() {
        System.out.print("能跑");
    }
    public void cry() {
        System.out.print("它是:");
    }
}

在创建一个Test类的类进行运行测试

package com.www.lenovo.demo;

public class Test {


public static void main(String[] args) {
    Animal a = new Cat();
    Animal b = new Dog();
    Animal c = new Pig();
    a.eat();
    a.run();
    a.cry();

    b.eat();
    b.run();
    b.cry();

    c.eat();
    c.run();
    c.cry();

   }

}

运行结果

这里写图片描述

猜你喜欢

转载自blog.csdn.net/piupipiupi/article/details/80352474