java的多态和final关键字

多态:

多态分为对象多态,行为多态

多态的前提:

有继承/实现关系;存在父类引用子类对象;存在方法重写;

注意:多态是对象,行为的多态,java的成员变量不谈多态

这是我写的三个类:

测试:

cpp 复制代码
public class test {
    public static void main(String[] args) {
        //对象多态(编译时看左边,运行时看右边)
        //编译时是people父类的run函数
        people p1=new teacher();
        people p2=new student();
        //行为多态
        p1.run();//teacher run
        p2.run();//student run

        //成员变量没有多态(编译看左边,运行还是看左边)
        System.out.println(p1.name);//父类people
        System.out.println(p2.name);//父类people
    }
}

使用多态的好处:

定义方法时,使用父类类型的形参,可以接收一切子类对象,扩展性更强

在多态形式下,右边的对象是解耦合的(可以随时切换)

缺点:

多态下不能使用子类的独有功能,只能用重写父类方法方法

解决方法:强制类型转换,把父类对象强转成子类对象

子类 对象名=(父类)父类对象

注意:强转前,使用instanceof关键字,判断当前对象的真实类型,再进行强转

java 复制代码
public class test {
    public static void main(String[] args) {
       people p1=new student();
       people p2=new teacher();

       student s1= (student) p1;
       s1.studentrun();

       //student s2= (student) p2;//ClassCastException

        if(p1 instanceof student)//是返回true
        {
            student s3= (student) p1;
            s3.studentrun();
        }
        if(p2 instanceof teacher)
        {
            teacher t1= (teacher) p2;
            t1.teacherrun();
        }


    }
}

final关键字:

修饰类:该类为最终类,不能被继承

修饰方法 :该方法为最终方法,不能被重写

修饰变量:该变量只能被赋值一次

变量:

1局部变量

2成员变量:

1静态成员变量

2实例成员变量

常量:

使用static final 修饰的成员变量就被称为常量

java 复制代码
public class test1 {
    public static final String NAME="hhh";

    public static void main(String[] args) {
        System.out.println(NAME);//hhh
    }
}
相关推荐
C语言小火车28 分钟前
QT面试题:内存管理与对象生命周期
开发语言·qt·面试
chaser&upper29 分钟前
Spring 服务调用接口时,提示You should be redirected automatically to target URL:
java
一切皆有迹可循3 小时前
IntelliJ IDEA中Spring Boot项目整合MyBatis:从零实现高效数据持久化
java·spring boot·intellij-idea·mybatis
雾月554 小时前
LeetCode 941 有效的山脉数组
java·开发语言·数据结构·算法·leetcode·职场和发展
晨曦5432105 小时前
函数和模式化——python
开发语言·python
leluckys5 小时前
swift-08-属性、汇编分析inout本质
开发语言·汇编·swift
小诸葛的博客6 小时前
Apache BookKeeper Ledger 的底层存储机制解析
java
半旧5186 小时前
重构谷粒商城11:node快速入门
java·前端·重构