java笔记--day09--多态和继承的微弱区别

  • 1 首先看一个多态的Demo:
class Fu{
    int num1 = 10;
    public Fu(){

    }

    public void show1(){
        System.out.println("num1 is " + num1);
    }
}

class Zi extends Fu{
    int num1 = 11;
    int num2 = 20;
    public Zi(){}
    public void show1(){
        System.out.println("num1 is " + num1);
    }
    public void show2(){
        System.out.println("num2 is " + num2);
    }
}

class PolymorphicDemo2{
    public static void main(String[] args) {
        Fu f = new Zi();
        System.out.println("num1 is " + f.num1); //member variable
        //System.out.println("num2 is " + f.num2); //This line must be commented out,or there is a fail during compilation.(error:can not find the symbol)

        f.show1();
        //f.show2();//This line must be commented out,or there is a fail during compilation.(error:can not find the symbol) 

    }
}

/*
running result:
num1 is 10
num1 is 11
*/
  • 2 再看一个继承的Demo:
class Fu{
    int num1;
    public Fu(){
        num1 = 10;
    }

    public void show1(){
        System.out.println("num1 is " + num1);
    }
}

class Zi extends Fu{
    int num1 = 11;
    int num2 = 20;
    public Zi(){}
    public void show1(){
        System.out.println("num1 is " + num1);
    }
    public void show2(){
        System.out.println("num2 is " + num2);
    }
}

class InheritDemo1{
    public static void main(String[] args) {
        Zi z = new Zi();
        System.out.println("num1 is " + z.num1); //member variable
        System.out.println("num2 is " + z.num2);
        System.out.println();
        z.show1();//member method
        z.show2();
    }
}

/*
running result:
num1 is 11
num2 is 20

num1 is 11
num2 is 20
*/
  • 3 小结
    • 3.1 由以上两个Demo可以看出,多态首先是建立在继承的基础之上的
    • 3.2 多态必须有方法重写,这增加了程序的扩展性
    • 3.3 多态中成员变量的特点是:编译看左边,运行看左边;成员方法的特点是:编译看左边,运行看右边
  • 4 多态总结
    • 多态其实就是:一个父类对象,其可以调用(子类中对父类中重写的)成员方法。起作用就是对父类的功能加以扩展
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值