当前位置: 首页> 教育> 大学 > java用this语句调用构造方法

java用this语句调用构造方法

时间:2025/7/10 21:48:46来源:https://blog.csdn.net/2301_81968528/article/details/140054611 浏览次数:1次

示例代码如下:

class Student7{private String name;private int age;public Student7(){System.out.println("调用了无参构造方法");}public Student7(String name,int age){this();this.name=name;this.age=age;}public String read(){return"我是:"+name+",年龄:"+age;}
}public class This2 {public static void main(String[] args) {// this调用构造方法Student7 stu=new Student7("张三",18);System.out.println(stu.read());}}

这段代码中,定义了一个无参构造方法和一个有参构造方法。

在有参构造方法代码片段中

public Student7(String name,int age){this();this.name=name;this.age=age;}

通过this()语句调用了无参构造方法

this调用类的构造方法时,必须只能在构造方法里调用,不能在成员方法里调用。

在构造方法里,this调用其他构造方法必须写在第一行。另外,一个类中两个调用方法不能互相调用

关键字:java用this语句调用构造方法

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: