最近搞android,发现自己对于java的基础还是不是很牢固,只能通过写博客进行总结和理解了,毕竟,书写是为了更好的思考。
任务描述
本关任务:使用this
关键字,设置对象的成员变量。
相关知识
我们先来看一段代码
输出结果: 传入的name:李四age:10
student属性name:张三age:18
上述结果我们可以发现一个问题,在构造方法中name
和age
并没有设置成功,stu
对象的name
属性和age
属性的值还是默认定义好的张三
和18
。
怎么解决这个问题呢?你需要学习两个知识点:1.什么是成员变量; 2.this
关键字。
什么是成员变量
成员变量就是对象的属性:
转存失败重新上传取消
this关键字
关于this
关键字,你只需要记住它就是指自身,this
即代表自己,this.属性
访问的是自己的属性、this()
访问的就是自己的无参构造方法。
例1:this.属性
转存失败重新上传取消
例2:this.属性,this()
转存失败重新上传取消
输出: I am
张三
可以发现,如果我们把上述this.name = name
改为 name = name
,那么最终的结果就变成了: I am
null
this()
调用的是Person
自己的无参构造方法,this.name
访问的是Person
对象自身的name
,而方法参数中的name
则表示方法传入的值。
学会了this
关键字的用法,那本关最开始遇到的问题是不是就有解了呢?
编程要求
右侧编辑器中已经编写好了代码,但是输出结果不能让我们满意,请根据所学知识修改代码,使其能输出如下结果: name:baby
age:45
sex:女
测试说明
测试输入: baby
,45
,女
预期输出: name:baby
age:45
sex:女
开始你的任务吧,祝你成功!
package step3;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = sc.next();
int age = sc.nextInt();
String sex = sc.next();
Person p = new Person(name,age,sex);
p.display();
}
}
class Person{
String name = "张三";
int age = 18;
String sex = "男";
/********** Begin **********/
public Person(String name,int age,String sex){
this(age);
this.name = name;
this.sex = sex;
}
public Person(int age){
this.age = age;
}
public void display(){
String name = "李四";
int age = 11;
String sex = "男";
System.out.println("name:" + this.name);
System.out.println("age:" + this.age);
System.out.println("sex:" + this.sex);
}
/********** End **********/
}
然后,便是this和super在继承中的不同之处,请看下面代码:
import java.util.Scanner; public class Main { static int x; static int y; static int z; public static void main(String[] args) { Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); z = in.nextInt(); Sub sub = new Sub( x, y, z); System.out.println(sub.calculate(x, y, z)); } public static class Base { int x, y; // } public static class Sub extends Base { int z; public Sub(int x, int y, int z) { this.x = x; //先访问Sub内的成员变量,如果Sub类内找不到,就会在父类内寻找 this.y = y; //或者 // super.x=x; // super.y=y; this.z = z; } public int calculate(int x, int y, int z) { return x * y * z; } } }