• Java中this和super的用法总结


    this

    this是自身的一个对象,代表对象本身,可以理解为:指向对象本身的一个指针。

    this的用法在java中大体可以分为3种:

    1.普通的直接引用

    this相当于是指向当前对象本身。

    2.形参与成员名字重名,用this来区分

    3.引用构造函数

    这个和super放在一起讲,见下面。

    super

    super可以理解为是指向自己父类对象的一个指针,而这个父类指的是离自己最近的一个父类。

    super也有三种用法:

    1.普通的直接引用

    与this类似,super相当于是指向当前对象的父类,这样就可以用super.xxx来引用父类的成员。

    2.子类中的成员变量或方法与父类中的成员变量或方法同名

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    class Country {
        String name;
        void value() {
           name = "China";
        }
    }
      
    class City extends Country {
        String name;
        void value() {
        name = "Shanghai";
        super.value();      //调用父类的方法
        System.out.println(name);
        System.out.println(super.name);
        }
      
        public static void main(String[] args) {
           City c=new City();
           c.value();
           }
    }

    运行结果:

    Shanghai
    China

    可以看到,这里既调用了父类的方法,也调用了父类的变量。若不调用父类方法value(),只调用父类变量name的话,则父类name值为默认值null。

    3.引用构造函数

    super(参数):调用父类中的某一个构造函数(应该为构造函数中的第一条语句)。
    this(参数):调用本类中另一种形式的构造函数(应该为构造函数中的第一条语句)。
  • 相关阅读:
    [Leetcode] Convert Sorted List to Binary Search Tree
    [Leetcode] Sqrt(x)
    [Leetcode] Pow(x, n)
    [Leetcode] Balanced Binary Tree
    [Leetcode] Convert Sorted Array to Binary Search Tree
    [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal
    [Leetcode] Remove Element
    [Leetcode] Letter Combinations of a Phone Number
    [Leetcode] Generate Parentheses
    [Leetcode] Valid Parentheses
  • 原文地址:https://www.cnblogs.com/insist-bin/p/11096382.html
Copyright © 2020-2023  润新知