一、JavaBean规范
在封装好一个类以后,应该把对象中的信息隐藏恰里(把类中的字段全部使用使用private修饰起来,其他类不能直接访问)。为了能让外界(其他类)访问本类中私有字段成员,我们专提供getter和setter方法。
public class Person{
//对象的字段是用来存储对象的数据的
private String name;
privat int age;
}
getter方法:用于获取某一字段存储的值。
public String getName(){
return name;//返回name字段存储的值
}
如果操作的字段是Boolean类型的,此时不应该叫getter方法,而是is方法,把getName变成isName.
setter方法:仅仅用于给某一字段设置需要存储的值。
public void setName(String name){
this.name = name;//把传过来的n参数的值存储到name字段中
}
每一个字段都得提供一对getter和setter方法,使用工具自动生成
idea中自动生成getter和setter方法
在编辑框中右击
选择generator
拖选住你想要生成geter、seter方法的属性,
点击完成即可自动生成geter和seter方法。
快捷键为:alt+insert
二、this关键字
2.1 什么是this
表示当前对象
this主要存在与两个位置:
构造器中:表示当前创建的对象
方法中:哪一个对象用this所在的方法,this就表示哪个对象。
2.2 this的几种用法
1.当成员变量和局部变量重名时,在方法中使用this时,表示的是该方法所在类中的成员变量。(this是当前对象自己)
public class Hello {
String s = "Hello";
public Hello(String s) {
System.out.println("s = " + s);
System.out.println("1 -> this.s = " + this.s);
this.s = s;//把参数值赋给成员变量,成员变量的值改变
System.out.println("2 -> this.s = " + this.s);
}
public static void main(String[] args) {
Hello x = new Hello("HelloWorld!");
System.out.println("s=" + x.s);//验证成员变量值的改变
}
}
结果:
s = HelloWorld!
1 -> this.s = Hello
2 -> this.s = HelloWorld!
s=HelloWorld!
2.把自己当作参数传递时,也可以用this.(this作当前参数进行传递)
class A {
public A() {
new B(this).print();// 调用B的方法
}
public void print() {
System.out.println("HelloAA from A!");
}
}
class B {
A a;
public B(A a) {
this.a = a;
}
public void print() {
a.print();//调用A的方法
System.out.println("HelloAB from B!");
}
}
public class HelloA {
public static void main(String[] args) {
A aaa = new A();
aaa.print();
B bbb = new B(aaa);
bbb.print();
}
}
结果为:
HelloAA from A!
HelloAB from B!
HelloAA from A!
HelloAA from A!
HelloAB from B!
3.有时候,我们会用到一些内部类和匿名类,如事件处理。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。如:
public class HelloB {
int i = 1;
public HelloB() {
Thread thread = new Thread() {
public void run() {
for (int j=0;j<20;j++) {
HelloB.this.run();//调用外部类的方法
try {
sleep(1000);
} catch (InterruptedException ie) {
}
}
}
}; // 注意这里有分号
thread.start();
}
public void run() {
System.out.println("i = " + i);
i++;
}
public static void main(String[] args) throws Exception {
new HelloB();
}
}
4.在构造函数中,通过this可以调用同一类中别的构造函数。如:
public class ThisTest {
private int age;
private String str;
ThisTest(String str) {
this.str=str;
System.out.println(str);
}
ThisTest(String str,int age) {
this(str);
this.age=age;
System.out.println(age);
}
public static void main(String[] args) {
ThisTest thistest = new ThisTest("this测试成功",25);
}
}
结果为:
this测试成功
25
==注意==:
1:在构造调用另一个构造函数,调用动作必须置于最起始的位置。
2:不能在构造函数以外的任何函数内调用构造函数。
3:在一个构造函数内只能调用一个构造函数。
5.this同时传递多个参数。
public class TestClass {
int x;
int y;
static void showtest(TestClass tc) {//实例化对象
System.out.println(tc.x + " " + tc.y);
}
void seeit() {
showtest(this);
}
public static void main(String[] args) {
TestClass p = new TestClass();
p.x = 9;
p.y = 10;
p.seeit();
}
}
结果为:9 10
代码中的showtest(this),这里的this就是把当前实例化的p传给了showtest()方法,从而就运行了。
Comments | NOTHING