Java this和super关键字

版权声明:欢迎访问ssm个人搭建博客 https://www.yanzhaochang.top 所有版权归静待花开所有 https://blog.csdn.net/qq_42081709/article/details/89924340

一  this关键字

    定义

        1. this关键字代表了所属函数的的调用者对象,this代表了对象的内存地址,它指向调用这个方法的对象。

        2. this关键字代表的是对象的引用,也就是this在指向一个对象,所指向的对象就是调用该函数的对象引用。

    作用:

        1. 区别成员变量和局部变量,可以通过this关键字来调用。

        2. 在构造函数中可以调用另一个构造函数初始化对象。

        3. this可以表示当前对象在方法中作为参数传递。

        4. this可以代表该方法对象的引用

     注意:

        1. 存在同名的成员变量和局部变量时,在方法内部访问的是局部变量(Java 采用的是就近原则机制)。

        2. 在一个变量只存在成员变量的情况下访问,Java编辑器默认会在变量的前面添加this关键字。

        3. this关键字调用其他的构造函数的时候,this关键字必须要位于构造函数的第一个语句。

        4. this关键字在构造函数中不能出现相互调用的情况。

        5. 不能在普通方法中(非构造方法)中调用其他构造方法。

    例:

  public class Demo {
	public static void main(String[] args) {
	    new People("410927XXXXXXX...", "张三",19);
	}
  }

  class People {
	private String id;
	private String name;
	private Integer age;

	public People(String id, String name) {
		this.id = id;// 区别局部变量和成员变量
		this.name = name;
	}
	public People(String id, String name, Integer age) {
		this(id, name);// 调用其他构造函数
		this.age = age;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	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;
	}
	
}

二 super关键字

     super关键字代表了父类空间的引用。

    作用:

        1. 子父类同时存在同名的成员(变量和方法)时,在子类中默认访问的是子类的成员,可以通过super关键字指向父类的成员

        2. 创建子类时,默认会调用父类无参的构造方法,可以通过super指定调用父类的构造函数

    注意:

       1. 如果在子类的构造函数上没有指定调用父类的构造函数,那么java 编译器默认会在子类构造函数第一行加上super()语句。

       2. super关键字调用父类的构造函数时,该语句必须是子类构造函数中的第一个语句。

       3. super 和 this关键字不能同时出现在一个构造函数中,因为两个关键字都要出现在方法的第一个语句,但是可以使用this.变量。

      例:

        People 类使用上面的测试类

    public class Demo {
	public static void main(String[] args) {
	    new Worker("410927XXXXXXX...", "张三",99999d);
	}
    }

    class Worker extends People {
	private Double money;
	
	public Worker(String id, String name,Double money) {
	    super(id, name);
	    System.out.println("身份证号:"+super.getId());
	    System.out.println("姓名:"+super.getName());
	    this.money = money;
	}
    }

    

  this 和 super的区别        

      1. 代表的事物不同

            super 代表的是父类空间的引用(并不是代表对象,只是对象的一块内存)

            this 代表的是所属函数的的调用者对象

      2. 使用前提不同

            super关键字必须要有继承的前提才能使用

            this关键字不需要继承关系即可使用

      3. 调用构造函数的区别

            super关键字调用的是父类的构造函数

            this关键字调用的是子类的构造函数

    

    

猜你喜欢

转载自blog.csdn.net/qq_42081709/article/details/89924340