用this调用构造函数
来源:互联网 发布:windows自动修复 编辑:程序博客网 时间:2024/06/15 23:49
public class H{ int petalCount=0; String s; H(String ss) { s=ss; print(s); } H(int petals) { petalCount=petals; print(petalCount); } H(String s,int petals) { this(s);//用this调用该类的构造函数 petalCount=petals; } public static void main(String[] args) { H flower1=new H(4);//4 H flowre2=new H("hello"); H flower3=new H("nihao",6); print(flower3.petalCount); } }
输出:
4
hello
nihao
6
public class H{ int petalCount=0; String s; H(String ss) { s=ss; print(s); } H(int petals) { petalCount=petals; print(petalCount); } H(String s,int petals) { this(s); this(petals); } public static void main(String[] args) { H flower1=new H(4); H flowre2=new H("hello"); H flower3=new H("nihao",6);//报错 因为只能在构造函数中使用一次this调用其他构造函数 } }
报错
public class H{ int petalCount=0; String s; H(String ss) { s=ss; print(s); } H(int petals) { petalCount=petals; print(petalCount); } H(String ss,int petals) { this(petals); s=ss; } public static void main(String[] args) { H flower1=new H(4); H flowre2=new H("hello"); H flower3=new H("nihao",6); print(flower3.s); } }
输出:
4
hello
6
nihao
知识点:
在构造函数中可以调用该类的其他构造函数,且在一个构造函中只能调用一次该类的其他构造函数,且这句调用语句必须写在本函数的第一行。
注意:不能在类的其他方法中使用this调用该类的构造函数。
public class H{ String s; H(String ss) { s=ss; print(s); } void prints() { this("123"); } public static void main(String[] args) { H a=new H("bilibili"); a.prints(); //报错,不能在类的其他方法中用this使用该类的狗仔函数 } }
package net.mindview;import static net.mindview.util.Print.*;// 要求类中有两个构造函数,且在第一个构造函数中用this调用第二个构造函数public class H{ int a; String str; H(int a1,String str1) { this(a1); str=str1; } H(int a1) { a=a1; } public static void main(String[] args) { H haha=new H(1,"hello world!"); print(haha.a); print(haha.str); } }
输出:
1
hello world!
阅读全文
0 0
- 用this调用构造函数
- 【构造函数】----构造函数调用构造函数,使用this
- Java中this调用重载构造函数
- c#之this显示调用构造函数
- 构造函数相互调用使用this指针
- 用this调用构造方法
- java 构造函数、非构造函数的this调用
- 5.this调用成员变量、成员函数、构造函数
- 用this调用类的构造方法
- 关于构造函数的重载 用this语句的调用问题
- JAVA学习,this(),super()调用构造函数研究
- 构造函数的this和super的调用
- 子父类构造函数的调用演示,区分this()和super()
- JAVA中super和this调用构造函数
- Java学习·this关键字在构造函数间调用
- 使用this调用本类中的其他构造函数
- this super 构造函数 以及 加载及调用顺序
- this用法-当前对象的引用与调用构造函数
- 设计模式之Builder模式
- 其他题目---设计RandomPool结构
- spring整合mybatis逆向工程+PageHelper插件
- [Lintcode] #175 翻转二叉树
- 高斯消元集合
- 用this调用构造函数
- ES 基本使用《三》--terms
- 解决svn中“工作副本已经锁定”,或者svn清理失败的解决方法
- Spinner自定义字体
- 《android日常bug系列》android studio意外重启后 原本的import全部报错
- 阿里云linux服务器支持ipv6为苹果过审
- Web过滤器
- 任意二维矩阵的可视化打印和查询(java)
- 关于泛型咱们应该知道的事情,才能写出更具有扩展性的代码