白板的微信
2018-10-05 10:48:52浏览 1422
1、
this: 是当前类的对象引用。简单的记,它就代表当前类的一个对象。
注意:谁调用这个方法,在该方法内部的this就代表谁。
this的场景:
解决局部变量隐藏成员变量
this:哪个对象调用那个方法,this就代表那个对象、
[代码]java代码:
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Student {
private String name;
private int age;
public String getName() {
return name; //这里其实是隐含了this
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class StudentTest2 {
public static void main(String[] args) {
//创建一个对象
Student s1 = new Student();
s1.setName("林青霞");
s1.setAge(27);
System.out.println(s1.getName()+"---"+s1.getAge());
//创建第二个对象
Student s2 = new Student();
s2.setName("刘意");
s2.setAge(30);
System.out.println(s2.getName()+"---"+s2.getAge());
}
}
|
2、构造方法:
给对象的数据进行初始化
格式:
A:方法名与类名相同
B:没有返回值类型,连void都没有
C:没有具体的返回值
我们一直在使用构造方法,但是,我们确没有定义构造方法,用的是哪里来的呢?
构造方法的注意事项:
A:如果我们没有给出构造方法,系统将自动提供一个无参构造方法。
B:如果我们给出了构造方法,系统将不再提供默认的无参构造方法。
注意:这个时候,如果我们还想使用无参构造方法,就必须自己给出。建议永远自己给出无参构造方法
给成员变量赋值有两种方式:
A:setXxx()
B:构造方法
[代码]java代码:
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | class Student {
private String name;
private int age;
public Student() {
//System.out.println("我给了,你还给不");
System.out.println("这是无参构造方法");
}
//构造方法的重载格式
public Student(String name) {
System.out.println("这是带一个String类型的构造方法");
this.name = name;
}
public Student(int age) {
System.out.println("这是带一个int类型的构造方法");
this.age = age;
}
public Student(String name,int age) {
System.out.println("这是一个带多个参数的构造方法");
this.name = name;
this.age = age;
}
public void show() {
System.out.println(name+"---"+age);
}
}
class ConstructDemo2 {
public static void main(String[] args) {
//创建对象
Student s = new Student();
s.show();
System.out.println("-------------");
//创建对象2
Student s2 = new Student("林青霞");
s2.show();
System.out.println("-------------");
//创建对象3
Student s3 = new Student(27);
s3.show();
System.out.println("-------------");
//创建对象4
Student s4 = new Student("林青霞",27);
s4.show();
}
}
|
原文链接:http://www.apkbus.com/blog-833059-61693.html