Java内容梳理(8)this和super关键字

this关键字

1.表示当前对象

当前正在执行该方法的对象

2.表示调用本类构造方法

this(...)

注意:this(...)这种代码需要放在构造方法中的第一句

举例:

    public Person() {
		//调用带有两个参数构造方法
		this("张三",18);
	}


	public Person(String name, int age) {
		this.name = name;
		this.age = age;
		System.out.println("带有两个参数的构造方法");
		
	}

super关键字

1. super. ==> 指代父类对象

通过 super. 来访问父类的属性和方法

super.父类属性名

super.父类方法名

2. super() ==> 调用父类构造方法

1.只能放在构造方法的第一句

2.若子类的构造方法中未明确编写super([参数])时,编译会自动为其添加一个super()

若我们在子类构造方法中明确编写了super([参数])时,则编译将不再添加

猜你喜欢

转载自blog.csdn.net/Carl_changxin/article/details/82728820