this
this
2023-09-27 14:23:51 时间
一:this 将对象传递给其它方法
package object; class Persion{ public void eat(Apple apple){ Apple peeled = apple.getPeeled(); System.out.println("Yummy"); } } class Peeler{ static Apple peel(Apple apple){ return apple; } } class Apple { Apple getPeeled(){return Peeler.peel(this);} /*Apple 需要调用Peeler.peel()方法. * 它是一个外部工具 将执行由于某种原因而必须放在Apple外部的操作 * 未将自身传递给外部方法.Apple必须使用关键字 */ } public class PassingThis{ public static void main(String[] args) { new Persion().eat(new Apple()); } } /** output: *Yummy */
二:this 可以调用构造器,单不能调用两个,此外,must 将构造器调用置于最起始处,否则编译器会报错
这个例子也展示了this的另一种用法 this.s ; 除构造器外编译器禁止在其它任何方法中调用构造器
//: object/Flower.java package object; import static net.mindview.util.Print.*; public class Flower{ int petalCount = 0; String s = "initial value"; Flower(int petals) { print("Constructor w/ int arg only, petalCount ="+petals); } Flower(String ss) { print("Constructor w/ String args only, s = "+ ss); s = ss; } Flower (String s, int petals) { this(petals); //! this(s); //Can't call two this.s=s; //Another use of "this" print("String & int args"); } Flower() { this("hi",47); print("default constructor (no args)"); } void printPetalCount() { //! this(11); //Not inside non-constructor! print("petalCount = " + petalCount+ " s = "+ s); } public static void main(String[] args) { Flower x = new Flower(); x.printPetalCount(); } }/** output; Constructor w/ int arg only, petalCount =47 String & int args default constructor (no args) petalCount = 0 s = hi *///:~
相关文章
- Python 成功解决报错 asyncio RuntimeError: This event loop is already running
- Unity 使用this关键字进行函数拓展 - Vector3
- Unity 使用this关键字进行函数拓展 - AudioSource
- js self = this的解释
- 【数据库开发】is not allowed to connect to this MySQL server解决办法
- 关于Mysql创建函数报错This function has none of DETERMINISTIC, NO SQL, 的解决方案
- [Err]1418 This function has none of DETERMINISTIC,NO SQL,or R
- Mixed Content: xxx This request has been blocked; the content must be served over HTTPS.
- JAVA中this的三种用法的详解
- 面向对象----构造方法、this 关键字、函数的参数传递、package语句/import语句
- Oracle study之--“ORA-00845: MEMORY_TARGET not supported on this system"错误
- 【Syntax error on token “}“, delete this token】Eclispe中代码报错!(已解决~)
- 使用sprintf格式化字符串出错:error C4996: 'sprintf': This function or variable may be unsafe.
- Vue中Vue.set()和this.$forceUpdate()的使用
- RN报错:Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
- jQuery中this与$(this)的差别
- 已解决Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
- he ‘kotlin-android-extensions‘ Gradle plugin is deprecated. Please use this migration guide
- 彻底掌握this,call,apply
- JavaScript this 总结(含 ES6)
- JQuery DOM clone(true),对于克隆对象事件触发后,处理函数中this指代克隆对象