zoukankan      html  css  js  c++  java
  • this/super

    java中,this用来指向或调用当前类的数据和方法,super用来调用父类的数据和方法。

    以下程序中通过对构造函数的调用来说明一些问题:

    1.在子类的一个构造函数中,不论this调用当前类的其他构造函数、或是super调用父类构造函数,都是放在子类的第一句,两者不能同时使用。

    2.如代码中注释所示

    this/super
     1 public class test
    2 {
    3 public static void main(String[] args)
    4 {
    5 new B();
    6 }
    7 }
    8
    9
    10 class A{
    11 A(){
    12 System.out.println("A中无参构造函数...");
    13 }
    14 A(int i,int j){
    15 System.out.println("A中有两个参数的构造函数...");
    16 }
    17 }
    18
    19 class B extends A{
    20 B(){
    21 // super(); //若与this(5)同时用,提示出错
    22 this(5); /* 2.此处不会直接调用super(),而是根据this(5)调用B(int i)先寻找是否有显式调用父类构造函数,
    23 最终在B(int i,int j)中找到,那么将调用super(int i,int j)构造函数;
    24 若找不到,则调用B()相应的A()构造函数*/
    25 System.out.println("B中无参构造函数...");
    26 }
    27 B(int i){
    28 this(i, i);
    29 System.out.println("B中只有一个参数的构造函数...");
    30 }
    31 B(int i,int j){
    32 super(i, j);
    33 System.out.println("B中有两个参数的构造函数...");
    34 }
    35 }


    输出结果:

    A中有两个参数的构造函数...
    B中有两个参数的构造函数...
    B中只有一个参数的构造函数...
    B中无参构造函数...
    
  • 相关阅读:
    正则表达式验证日期(多种日期格式)——转载
    NPOI导出Excel——精简版
    Ubuntu下安装部署.NET Core多版本环境
    搭建 nuget 私用库 BaGet
    ubuntu 监听端口
    搭建npm 私用库 verdaccio
    pgsql 性能测试 pgbench
    docker-compose 创建网络
    安装 docker-compose 启动
    dotnet sdk安装以及环境变量设置 Ubuntu 18.04 LTS
  • 原文地址:https://www.cnblogs.com/chenbin7/p/2242206.html
Copyright © 2011-2022 走看看