Java learning this point when calling the parent class constructor when instantiating a subclass 1-

Java learning this point when calling the parent class constructor when instantiating a subclass 1-

 

Java long war, to pick up a lot of problems encountered previously basics almost forgotten, can not go out to take advantage of multi-Learning.

Subclass through new forms instantiated, it will call the constructor of the parent class, then who this time this key point in the parent class is it? Take a look through the actual code.

Animal superclass

public class Animal {

    private String name;

    private Integer age;

    public void print(){
        System.out.println("super class");
    }

    public Animal(String name, Integer age) {
        this.name = name;
        this.age = age;
        this.print();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

Cat subclass

public class Cat extends Animal{

    private String color;


    public void print(){
        System.out.println("sub class");
    }

    public Cat(String name,Integer age,String color) {
        super(name,age);
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

Test class MainTest


public class MainTest {

    public static void main(String[] args) {

        Cat cat = new Cat("aa",12,"red");


    }
}

Output Structure

sub class

This structure can be seen from the parent class constructor example of this keyword does point to a subclass.

In this case determining the type of the parent class's constructor

public Animal(String name, Integer age) {
        this.name = name;
        this.age = age;
        this.print();
        if(this instanceof Cat){
            System.out.println("just is a cat !");
        }
    }

Executed again

sub class
just is a cat !

Indeed point to a subclass.

Deeper principle, I have to look at the relationship when the usage of this and the presence of inheritance class loader.

Published 96 original articles · won praise 22 · views 310 000 +

Guess you like

Origin blog.csdn.net/chuan_day/article/details/104109964