当前位置: 首页 > news >正文

Java中的super关键字

super 是Java中的一个关键字,它可以用来引用当前对象的父类(超类)的成员变量或方法。主要有以下用途:

  1. 访问父类的成员变量

    • 当子类和父类中有同名的成员变量时,可以使用super关键字来访问父类的成员变量。
    class Parent {int x = 10;
    }class Child extends Parent {int x = 20;void display() {System.out.println(x); // 输出子类的x,即20System.out.println(super.x); // 输出父类的x,即10}
    }
    
  2. 调用父类的构造方法

    • 在子类的构造方法中,可以使用super来调用父类的构造方法。
    class Parent {int x;Parent(int x) {this.x = x;}
    }class Child extends Parent {int y;Child(int x, int y) {super(x); // 调用父类的构造方法this.y = y;}
    }
    
  3. 访问父类的方法

    • 当子类和父类中有同名的方法时,可以使用super关键字来调用父类的方法。
    class Parent {void display() {System.out.println("Parent");}
    }class Child extends Parent {void display() {super.display(); // 调用父类的display方法System.out.println("Child");}
    }
    
  4. 在子类构造方法中调用父类的构造方法

    • 当子类的构造方法中没有使用super来调用父类的构造方法时,会默认调用父类的无参构造方法。
    class Parent {int x;Parent(int x) {this.x = x;}
    }class Child extends Parent {int y;Child(int y) {this.y = y;// super(); // 默认调用父类的无参构造方法}
    }
    

总的来说,super关键字可以用于在子类中访问父类的成员、调用父类的构造方法以及调用父类的方法,从而实现对父类的重用。

http://www.lryc.cn/news/176380.html

相关文章:

  • MySQL数据库入门到精通6--进阶篇(锁)
  • js的继承
  • HONEYWELLL 05701-A-0325 控制脉冲模块
  • Qt扩展-QCustomPlot 简介及配置
  • python教程:selenium WebDriver 中的几种等待--sleep(),implicitly_wait(),WebDriverWait()
  • 从裸机开始安装操作系统
  • redhat 6.1 测试环境安装 yum
  • WARNING:tensorflow:Your input ran out of data; interrupting training. 解决方法
  • ChunJun(OldNameIsFlinkX)
  • MySQL的时间差函数、日期转换计算函数
  • 【神印王座】悲啸洞穴之物揭晓,圣采儿差点被骗,幸好龙皓晨聪明
  • 性能测试之使用Jemeter对HTTP接口压测
  • Spring面试题13:Spring中ApplicationContext实现有哪些?Bean工厂和Applicationcontext有什么区别
  • Spring 学习(六)代理模式
  • Educational Codeforces Round 155 (Rated for Div. 2) - D Sum of XOR Functions
  • [C++ 网络协议] I/O流分离所带来的半关闭问题
  • 根据文章段落内容自动插入图片php版
  • 在GEHC的第一个sprint记录
  • MFC 绘图
  • 算法 用两个栈实现队列-(栈+队列)
  • Android单编模块报FAILED: ninja: unknown target ‘MODULES-IN-vendor错误解决
  • 地球的某一片红薯地中秋圆《乡村振兴战略下传统村落文化旅游设计》——旅行季许少辉八月新书辉少许想象和世界一样宽广
  • Zookeeper-命令操作
  • eclipse 添加注释
  • Linux网络编程- 网络字节顺序
  • 如何永久关闭WPS任务窗口?
  • Cesium 问题:加载 geojson 数据量大浏览器会崩,使用primitive方式加载
  • C++ Primer----1.5类简介 章节练习
  • 爬楼梯Java(斐波那契数列)
  • Maven项目package为jar包后在window运行报A JNI error has occurred