zoukankan      html  css  js  c++  java
  • JAVA基础-多态

    需要掌握的知识点

    1. 理解多态的概念
    2. 理解对象的类型转换(父子类之间)
    3. 熟练掌握instanceof关键字
    4. 理解父类作为方法形参实现的多态
    5. 理解父类作为返回值实现的多态

    多态的向上转型

    同一个引用类型,使用不同的实例而执行不同操作
    父类类型 变量 = new 子类A构造器(形参);
    父类类型 变量 = new 子类B构造器(形参);

    下面是一个例子:父亲类型当做方法参数,父亲类型可以接受子类的类型

    //打印机父类
    public class Printer {
    
        String Name = "Father!!";
    
    	public void print() {
    		System.out.println("Print father!");
    	}
    
    }
    
    //打印机黑白
    public class BPrinter extends Printer{
    
        String Name = "BLACK!!";
    
    	@Override
    	public void print() {
    		// TODO Auto-generated method stub
    		System.out.println("黑白纸张!!");
    	}
    }
    
    
    
    //打印机彩色
    public class CPrinter extends Printer{
    
        String Name = "BLACK!!";
    
    	@Override
    	public void print() {
    		// TODO Auto-generated method stub
    		System.out.println("彩色纸张!!!");
    	}
    }
    
    
    public class Master {
    
    	//父亲类型当做方法参数!
    	public void mprint(Printer p ) {
    		p.print();
    	}
    	
    	
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		
            //如果子类方法重写,调用的是子类的方法
    		Master Jeason = new Master();
    		BPrinter p1 = new BPrinter();
    		CPrinter p2 = new CPrinter();
    		Jeason.mprint(p1);
    		Jeason.mprint(p2);
    
            //调用的父类成员变量
            Printer p = new BPrinter();
    		System.out.println( p.name );
    	}
    }   
    
    // 输出:
    // 黑白纸张!!
    // 彩色纸张!!!
    // printer father!!
    

    上面的这个过程叫做向上转型
    总结一下:

    • 向上转型时,父类中与子类成员变量相同时,输出成员变量时调用的是父类的成员变量。
    • 向上转型时,优先调用子类中重写的方法。

    多态的向下转型

    向下转型就是父类转换成子类(强制转换)
    前提是要先进行向上转型:

    Printer p = new BPrinter();
    BPrinter p3 = (BPrinter)p;
    

    其中我们可以借用instanceof运算法先进性判断,随后进行强制转换

  • 相关阅读:
    周末之个人杂想(十三)
    PowerTip of the DaySorting Multiple Properties
    PowerTip of the DayCreate Remoting Solutions
    PowerTip of the DayAdd Help to Your Functions
    PowerTip of the DayAcessing Function Parameters by Type
    PowerTip of the DayReplace Text in Files
    PowerTip of the DayAdding Extra Information
    PowerTip of the DayPrinting Results
    Win7下IIS 7.5配置SSAS(2008)远程访问
    PowerTip of the DayOpening Current Folder in Explorer
  • 原文地址:https://www.cnblogs.com/JeasonIsCoding/p/13232487.html
Copyright © 2011-2022 走看看