杰瑞科技汇

this和super在Java中到底有何区别?

Of course! this and super are two fundamental keywords in Java that are essential for object-oriented programming. They both refer to objects, but they do so in different ways and for different purposes.

Let's break them down one by one.


this Keyword

The this keyword in Java is a reference to the current object—the object whose method or constructor is currently being called.

Think of it as a pronoun like "my" or "this". When you say "my car", you're referring to the car that belongs to you. Similarly, when you use this, you're referring to the object that "owns" the current piece of code.

Main Uses of this:

  1. To Refer to Instance Variables: When a method's parameter has the same name as an instance variable, this is used to distinguish between them and access the instance variable.

    public class Person {
        private String name; // Instance variable
        // Constructor parameter 'name' shadows the instance variable 'name'
        public Person(String name) {
            // 'this.name' refers to the instance variable of the class
            // 'name' refers to the constructor parameter
            this.name = name;
        }
        public void printName() {
            System.out.println(this.name); // 'this.name' is clear, but 'name' would also work here
        }
    }
  2. To Invoke Current Class Method: You can use this to explicitly call a method from the current class. While often redundant, it can be useful in complex scenarios or for clarity.

    public class Calculator {
        public void add(int a, int b) {
            System.out.println("Sum: " + (a + b));
        }
        public void performCalculation(int x, int y) {
            System.out.println("Performing calculation...");
            this.add(x, y); // Explicitly calling the add method of the current object
        }
    }
  3. To Invoke Current Class Constructor: This is a very powerful feature. You can use this() to call another constructor from within the same class. This is called constructor chaining. It helps avoid code duplication.

    • Rules:
      • It must be the first statement in the constructor.
      • You cannot have this() and super() in the same constructor.
    public class Student {
        private String name;
        private int age;
        // Constructor 1: No-args constructor
        public Student() {
            // Calls the second constructor, providing default values
            this("Unknown", 0);
        }
        // Constructor 2: Parameterized constructor
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public String toString() {
            return "Student [name=" + name + ", age=" + age + "]";
        }
    }
    // Usage:
    Student s1 = new Student(); // Calls constructor 1, which then calls constructor 2
    System.out.println(s1); // Output: Student [name=Unknown, age=0]
    Student s2 = new Student("Alice", 20);
    System.out.println(s2); // Output: Student [name=Alice, age=20]

super Keyword

The super keyword in Java is a reference to the parent class object (also called the superclass or base class). It's used to access members (variables and methods) of the parent class from within a subclass.

Think of it as a way to "look up" to the parent class.

Main Uses of super:

  1. To Access Parent Class Instance Variable: When a subclass has a variable with the same name as a variable in the parent class, super is used to access the parent's variable.

    class Animal {
        String color = "white"; // Parent class variable
    }
    class Dog extends Animal {
        String color = "black"; // Child class variable
        public void printColor() {
            System.out.println("Dog's color: " + this.color); // Child's color
            System.out.println("Animal's color: " + super.color); // Parent's color
        }
    }
    // Usage:
    Dog d = new Dog();
    d.printColor();
    // Output:
    // Dog's color: black
    // Animal's color: white
  2. To Invoke Parent Class Method: You can use super to call a method from the parent class. This is useful when you want to add some functionality to the parent's method without completely overriding it (this is called "method extension" or using the super keyword within an overridden method).

    class Vehicle {
        void run() {
            System.out.println("Vehicle is running");
        }
    }
    class Car extends Vehicle {
        @Override
        void run() {
            // First, call the parent's run method
            super.run();
            // Then, add new functionality specific to Car
            System.out.println("Car is running safely");
        }
    }
    // Usage:
    Car myCar = new Car();
    myCar.run();
    // Output:
    // Vehicle is running
    // Car is running safely
  3. To Invoke Parent Class Constructor: This is crucial for inheritance. When you create an object of a subclass, the constructor of the parent class is always called first to ensure the parent's part of the object is properly initialized. You can use super() to explicitly call a specific parent constructor.

    • Rules:
      • If you don't write a super() call, Java automatically inserts a call to the parent's no-argument constructor (super();) as the first line of the child's constructor.
      • If the parent class has no no-argument constructor, you must explicitly use super() to call one of the parent's existing constructors.
      • Like this(), super() must be the first statement in the constructor.
      • You cannot have both this() and super() in the same constructor.
    class Animal {
        Animal() {
            System.out.println("Animal constructor is called");
        }
    }
    class Dog extends Animal {
        Dog() {
            // super() is implicitly called here by the compiler.
            // We can make it explicit:
            super();
            System.out.println("Dog constructor is called");
        }
    }
    // Usage:
    Dog d = new Dog();
    // Output:
    // Animal constructor is called
    // Dog constructor is called

this vs. super: A Quick Comparison

Feature this super
Reference Refers to the current object. Refers to the parent class object.
Purpose To access members of the current class. To access members of the parent class.
Variables Resolves name conflicts between instance variables and parameters. Resolves name conflicts between child and parent class variables.
Methods Invokes methods of the current class. Invokes methods of the parent class.
Constructors Invokes other constructors in the same class (this()). Invokes constructors in the parent class (super()).
Inheritance Unrelated to inheritance. Fundamental to inheritance.

Summary

  • Use this when you need to refer to the current object. It's useful for disambiguating variable names, calling other methods in the same class, or chaining constructors within the same class.
  • Use super when you need to refer to the parent class. It's essential for accessing parent variables/methods and, most importantly, for ensuring the parent class is properly initialized when you use inheritance.
分享:
扫描分享到社交APP
上一篇
下一篇