zoukankan      html  css  js  c++  java
  • Java 动态绑定和多态

    动态绑定和多态

    • 动态绑定是指:"在执行程序期间(而非编译期间),判断引用所指对象的实际类型,调用其相应的方法。"
    • 动态绑定(多态)存在的条件
      1. 要有继承。
      2. 要有重写。
      3. 父类引用指向子类对象。
    • 当条件满足时,当调用父类里面重写的方法时,根据实际的对象来调用方法。
    • 例子
    class Animal
    {
    	private String name;
    	Animal(String name)
    	{
    		this.name = name;
    	}
    	public void enjoy()
    	{
    		System.out.println("叫声。。。。。");
    	}
    }
    class Cat extends Animal
    {
    	private String eyescolor;
    	Cat(String name,String eyescolor)
    	{
    		super(name);
    		this.eyescolor = eyescolor;
    	}
    	public void enjoy()                 //重写enjoy方法
    	{
    		System.out.println("猫叫声。。。。。");
    	}
    }
    class Dog extends Animal
    {
    	private String furcolor;
    	Dog(String name,String furcolor)
    	{
    		super(name);
    		this.furcolor = furcolor;
    	}
    	public void enjoy()                 //重写enjoy方法
    	{
    		System.out.println("狗叫声。。。。。");
    	}
    }
    class Lady
    {
    	private String name;
    	private Animal pet;
    	Lady(String name,Animal pet)
    	{
    		this.name = name;
    		this.pet = pet;
    	}
    	public void myPetEnjoy()
    	{
    		pet.enjoy();                   //调用时根据pet指向的实际类型来调用enjoy方法
    	}
    }
    public class Main
    {
    	public static void main(String args[])
    	{
    		Cat c = new Cat("catname","blue");
    		Dog d = new Dog("dogname","black");
    		Lady l1 = new Lady("l1",c);
    		Lady l2 = new Lady("l2",d);
    		l1.myPetEnjoy();
    		l2.myPetEnjoy();
    	}
    	
    }
    输出:
    猫叫声。。。。。
    狗叫声。。。。。
    
    
    

    Java中方法的存储方式


    • Java中的方法储存在Code segment中,每个方法都有一个指向它的指针。
  • 相关阅读:
    Servlet 生命周期
    深度学习笔记(十)Augmentation for small object detection(翻译)
    fast.ai(零)windows + pytorch 0.4
    win10 + cuda8.0 + caffe SSD + vs2015 + python3
    PyTorch(二)Intermediate
    PyTorch(一)Basics
    Caffe 使用记录(五)math_functions 分析
    win10 + gluon + GPU
    python tricks
    深度学习笔记(九)感受野计算
  • 原文地址:https://www.cnblogs.com/031602523liu/p/8654188.html
Copyright © 2011-2022 走看看