• 【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());
    	}
    
    }
    
  • 相关阅读:
    centos7安装sshd
    Linux搭建redist-cluster集群
    nginx离线安装,反向代理,负载均衡
    2017/12/31Java基础学习——数组输出の通过Arrays.toString()方法
    Java代码编写规范
    2017/12/27java基础学习——遇到的不懂问题
    2017/12/23Java基础学习——如何通过记事本编写代码,并通过dos界面运行Java源文件
    ZOJ3880 Demacia of the Ancients【序列处理+水题】
    ZOJ3869 Ace of Aces【序列处理】
    ZOJ3872 Beauty of Array【DP】
  • 原文地址:https://www.cnblogs.com/Neo007/p/6871912.html
Copyright © 2020-2023  润新知