笔记10 this 关键字

来源:互联网 发布:java 包装加密 编辑:程序博客网 时间:2024/06/06 03:24
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() );}}


 

 

0 0