博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于Java继承-继承以后构造器的实现
阅读量:4179 次
发布时间:2019-05-26

本文共 1092 字,大约阅读时间需要 3 分钟。

子类不能继承父类的构造器(构造方法或者构造函数),但是父类的构造器带有参数的,则必须在子类的构造器中显式地通过super关键字调用父类的构造器并配以适当的参数列表。

class A {
private int n; A(int n) { System.out.println("A(int n)"); this.n = n; } } class B extends A{
private int n; B(){ super(300); System.out.println("B"); } } public class TestSuperSub{
public static void main (String args[]){ B b = new B(); } }

输出

A(int n)B

如果父类有无参构造器,则在子类的构造器中不是必须得用super调用父类构造器,如果没有使用super关键字,系统会自动调用父类的无参构造器。

class A {
private int n; A(){ System.out.println("A()"); } A(int n) { System.out.println("A(int n)"); this.n = n; } } class B extends A{
private int n; B(){ super(300); System.out.println("B"); } public B(int n){ System.out.println("B(int n):"+n); this.n = n; } } public class TestSuperSub{
public static void main (String args[]){ B b1 = new B(); B b2 = new B(200); } }

输出

A(int n)BA()B(int n):200

转载地址:http://irlai.baihongyu.com/

你可能感兴趣的文章
android studio SDK开发
查看>>
studio 统计代码的行数
查看>>
字符数组和16进制互换
查看>>
PHP项目中出现致命错误: Class 'Redis' not found
查看>>
There is no tracking information for the current branch.
查看>>
fatal: refusing to merge unrelated histories
查看>>
Git命令还原未提交的变更
查看>>
Linux系统中环境变量的配置
查看>>
Linux系统中配置脚本程序开机启动
查看>>
让Linux系统上的nginx支持php程序
查看>>
源码编译安装LNMP环境之Nginx篇
查看>>
源码编译安装LNMP环境之PHP篇
查看>>
Linux中rpm工具使用教程
查看>>
Linux中yum工具使用教程
查看>>
JS最佳实践——单例模式
查看>>
为php添加gd库支持
查看>>
$'\r': command not found
查看>>
bash脚本:一键安装MYSQL5.6
查看>>
javascript实现压缩图片
查看>>
webpack教程
查看>>