【JAVA语法】04Java-多态性

本文介绍了Java中多态性的概念及其实现方式,包括方法的重载与重写及对象的向上转型和向下转型。同时讲解了instanceof关键字的使用,并通过示例展示了接口的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 多态性
  • 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());
    }

}

转载于:https://www.cnblogs.com/Neo007/p/6871912.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值