zoukankan      html  css  js  c++  java
  • 【JAVA语法】04Java-多态性

    • 多态性
    • instanceof 关键字
    • 接口的应用

    一、多态性

    1.多态性的体现:
    方法的重载和重写

    对象的多态性

    2.对象的多态性:

    • 向上转型: 程序会自动完成
      父类 父类对象 = 子类实例

    • 向下转型: 强制类型转换
      子类 子类对象 = (子类)父类实例

    class A{
    	public void tell1(){
    		System.out.println("A--tell1");
    	}
    	
    	public void tell2(){
    		System.out.println("A--tell2");
    	}
    }
    
    
    class B extends A{
    	public void tell1(){
    		System.out.println("B--tell1");
    	}
    	
    	public void tell3(){
    		System.out.println("B--tell3");
    	}
    }
    public class test01 {
    	
    	
    
    	public static void main(String[] args) 
    	{
    		//向上转型——系统自动完成
    		B b = new B();
    		A a = b;	//子类对象赋值给父类对象
    		a.tell1();  //方法重写,output :B--tell1
    		a.tell2();	//OUTPUT: A--tell2
    		
    		
    		
    		//向下转型——强制转换
    		A a = new B(); //子类赋值给父类,部分匹配
    		B b = (B)a;
    		b.tell1();
    		b.tell2();
    		b.tell3();
    		OUTPUT:
    				B--tell1
    				A--tell2
    				B--tell3
    	}
    		
    	}
    

    二、instanceof关键字

    2.1 用于判断一个对象到底是不是一个类的实例
    返回值为布尔类型

    class A{
    	public void tell1(){
    		System.out.println("A--tell1");
    	}
    	
    	public void tell2(){
    		System.out.println("A--tell2");
    	}
    }
    
    
    class B extends A{
    	public void tell1(){
    		System.out.println("B--tell1");
    	}
    	
    	public void tell3(){
    		System.out.println("B--tell3");
    	}
    }
    public class test01 {
    	
    	
    
    	public static void main(String[] args) 
    	{
    		A a = new A ();
    		System.out.println(a instanceof A);
    		System.out.println(a instanceof B);
    		
    		A a1 = new B ();
    		System.out.println(a1 instanceof A);
    		System.out.println(a1 instanceof B);
    	}
    		
    	}
    
    
    	OUTPUT:
    	true
    	false
    	true
    	true
    
    

    三、接口应用

    interface USB{
    	void start();
    	void stop();
    }
    class C {
    	public static void work(USB u ){
    		u.start();
    		System.out.println("Working");
    		u.stop();
    	}
    }
    
    class USBdisk implements USB{
    	public void start(){
    		System.out.println("the USB Disk is working");
    	}
    	public void stop(){
    		System.out.println("the USB Disk stopped");
    	}
    }
    
    public class inter01 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		C.work(new USBDisk());
    	}
    
    }
    
  • 相关阅读:
    写给大数据开发初学者的话 | 附教程
    Mysql 到 Hbase 数据如何实时同步,强大的 Streamsets 告诉你
    如何学习大数据?阿里大数据开发师分享学习知识
    最简大数据Spark2.1.0
    从技术 Leader 的招聘需求看,如何转岗为当前紧缺的大数据相关人才?
    Redis内核原理及读写一致企业级架构深入剖析1综合组件环境实战
    为什么85%的大数据项目总是失败?
    js中的this关键字
    php百度api调用简单实例
    nginx常用命令
  • 原文地址:https://www.cnblogs.com/Neo007/p/6871912.html
Copyright © 2011-2022 走看看