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中无参构造函数...
    
  • 相关阅读:
    android:重写返回键动画
    获得今天零点时间戳(转)
    【转】完美解决Android 9.0以上HTTP网络请求被限制问题
    Java的三种取整方法
    thymeleaf控制checkbox的选中状态回显
    thymeleaf控制checkbox的value值
    Supervisor 简单使用
    关于Requests代理,你必须知道的
    py-spy 常见问题及使用说明
    记一次Scrapy进程卡死的Debug过程
  • 原文地址:https://www.cnblogs.com/chenbin7/p/2242206.html
Copyright © 2011-2022 走看看