初探java中this的用法
2024-10-18 21:27:01
一般this在各类语言中都表示“调用当前函数的对象”,java中也存在这种用法:
public class Leaf {
int i = 0;
Leaf increment(){
i++;
return this; //this指代调用increment()函数的对象
}
void print(){
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();
} }
//////////out put///////////
//i = 3
在上面的代码中,我们在main()函数里首先定义了Leaf类的一个对象:x 。然后通过这个对象来调用increment()方法, 在这个increment()方法中返回了this--也就是指代调用它的当前对象x (通过这种方式就实现了链式表达式的效果)。
我们通过x.increment()来表示通过x来调用increment()函数,实际上在java语言内部这个函数的调用形式是这样子的:
Leaf.increment(x);
当然,这种转换只存在与语言内部,而不能这样写码。
另外一种情况是在构造函数中调用构造函数时,this指代一个构造函数,来看一个简单的例子:
public class Flower {
int petalCount = 0;
String s = "initial value";
Flower(int petals){
petalCount = petals;
System.out.println("Constructor w/ int arg only, petalCount = " + petalCount);
} Flower(String ss){
System.out.println("Constructor w/ string arg only, s = " + ss);
s = ss;
} Flower(String s, int petals){
this(petals); //这里的"this"指代的Flower构造器
this.s = s;
System.out.println("string and int args");
} Flower(){
this("hi", 47); //这里的"this"指代的Flower构造器
System.out.println("default (no args)");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Flower();
}
}
////////Out put/////////////
//Constructor w/ int arg only, petalCount = 47
//string and int args
//default (no args)
Flower类有四个构造函数,在这写构造函数内部的this表示也是Flower类的构造函数,而且this()中的参数的个数也指代对应的构造函数,这样就实现了在构造函数中调用其他的构造函数。
但是需要注意的一点就是:虽然我们可以通过this在一个构造函数中调用另一个构造函数,但是我们顶多只能用这种方法调用一次,而且对另一个构造函数的调用动作必须置于最起始处,否则编译器会发出错误消息。比方说,下面这样是不行的:
Flower(String s, int petals){
this(petals);
this(s); //error! 顶多只能调用this()一次。
}
最新文章
- SQL Server 2012 新特性
- Git------Win7系统使用TortoiseGit
- js浏览器对象的属性和方法
- 【转】身份证号码校验与信息提取 - Java 代码
- poj 1804 (nyoj 117)Brainman : 归并排序求逆序数
- oracle odbc配置
- C#类索引器的使用
- MEF依赖注入调试小技巧!
- [Mugeda HTML5技术教程之13]链接的添加方式
- Bootstrap Table的使用
- 开源分享 Unity3d客户端与C#分布式服务端游戏框架
- Windows下搭建Redis服务器
- 用户不再sudoers文件中
- Codeforces Round #429 (Div. 2)
- VcCallC#_02
- 第八章 计时器(BEEPER2)
- JSTORM 问题排查
- 使用Bootstrap 3开发响应式网站实践03,轮播下方的内容排版
- spring boot(4)-html和templates
- POJ 3348 Cows 凸包 求面积
热门文章
- java基础集合经典训练题
- gentoo 安装
- React的使用与JSX的转换
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(76)-微信公众平台开发-网页授权
- .net 大型分布式电子商务架构说明
- WebGIS项目中利用mysql控制点库进行千万条数据坐标转换时的分表分区优化方案
- from表单提交数据之后,后台对象接受不到值
- Android 微信第三方登录(个人笔记)
- docker4dotnet #4 使用Azure云存储构建高速 Docker registry
- Help Hanzo (素数筛+区间枚举)