java learning --super and this

Simply put, this refers to an instance of the current object or class; super is a special keyword for calling the parent class in inheritance

 

Knowledge points:

1 To call the hidden variable of the parent class through super, the getter method must be declared in the parent class, because the data members declared as private are not visible to the child class.

 

public class Demo{
    public static void main(String[] args) {
        Dog obj = new Dog();
        obj.move();
    }
}
class Animal{
    private String desc = "Animals are human's good friends";
    // must declare a getter method
    public String getDesc() { return desc; }

    public void move(){
        System.out.println("Animals can move");
    }
}
class Dog extends Animal{
    public void move(){
        super.move(); // call the super class method
        System.out.println("Dogs can walk and run");
        // Call the parent class hidden variable through the getter method
        System.out.println("Please remember: " + super.getDesc());
    }
}

 

 

2 When the member variable has the same name as the parameter inside the method, the role of this is displayed. Of course, all methods and properties of this object can be called through this.

public class Demo{
    public String name;
    public int age;
  
    public Demo(String name, int age){
        this.name = name;
        this.age = age;
    }
  
    public void say(){
        System.out.println("The name of the site is " + name + ", has been established " + age + "year");
    }
  
    public static void main(String[] args) {
        Demo obj = new Demo("Weixueyuan", 3);
        obj.say();
    }
}

 

 

 

 

Note: Either super() or this() must be placed on the first line of the constructor.

  • When calling another constructor in a constructor, the calling action must be placed at the very beginning.
  • A constructor cannot be called within any method other than a constructor.
  • Only one constructor can be called within a constructor.

If you write a constructor that neither super() nor this() is called, the compiler will automatically insert a call into the superclass constructor with no arguments. 

Finally, pay attention to the difference between super and this: super is not a reference to an object, you cannot assign super to another object variable, it is just a special keyword that instructs the compiler to call the superclass method.

 

The examples in this article are referenced from: http://www.weixueyuan.net

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326290327&siteId=291194637