笔记10 this 关键字

本文详细介绍了Java语言中this关键字的两种使用方式及其注意事项,并通过具体示例解释了如何使用this来调用同一类中的不同构造器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

this关键字的使用
package test0904;

/*		java语言中的特殊关键字:  this 
  		
  		this 关键字的使用方式有两种:
  			1) this.属性  或  this.方法 	它代表 "当前对象"
  			2) this() 或 this(参数列表) 	代表本类(当前对象)的构造器
  				
		this 关键字在使用时应注意什么?
			1) 	this 关键字不能在静态方法中使用。
			
			2) 	this关键字以 " this()或this(参数列表) "方式出现时,它一定
				在本类的构造器中使用并且一定是在第一行出现。				
						注意: 在java语言中规定: 本类的构造器可以相互调用。 
		举例:	class  Dog {
					private String name;
					private boolean sex;
					private int age;
										
					//静态变量(类变量)
					public static int counter = 0; //计数器
					
					public Dog() {			默认构造器,存放类变量计数器 counter;
						counter++; //计数  
					}
					public Dog( String name, boolean sex, int age ){
						this();				this 在这里,调用本类的默认构造器;
						//counter++; //计数
						this.name = name;
						this.sex = sex;
						this.age = age;
					}
				}
 */
public class ThisFlower {
		private String name;
		private double price;
		
		public ThisFlower() {
			this.name = "rose";
			this.price = 10 ;
		}
		public ThisFlower( String name, double price ){
			this.name = name;
			this.price = price;
		}				
		public ThisFlower raisePrice( ){
			this.price += 10;		//此花涨价了;
			return this ; 							//将当前对象反馈出去
			// return new ThisFlwoer() ; 创建一个新的对象Flower并反馈出去;
		}		
		public String toString(){
			return "花名: " + name + "  花的价格: " + price + " 元/支。";
		}
		//应用本类;
		public static void main(String[] args) {
			ThisFlower  f1 = new ThisFlower( "rose", 10 );
			
			System.out.println( f1.toString() );
			
			f1.raisePrice().raisePrice().raisePrice().raisePrice().raisePrice(); //涨价5次
			System.out.println( f1.toString() );
		}
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值