• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

详解Java使用super和this来重载构造方法

java 搞代码 4年前 (2022-01-05) 18次浏览 已收录 0个评论

这篇文章主要介绍了详解Java使用super和this来重载构造方法的相关资料,这里提供实例来帮助大家理解这部分内容,需要的朋友可以参考下

详解Java使用super和this来重载构造方法

实例代码:

 //父类 class anotherPerson{ String name = ""; String age = ""; public String getAge() { return age; } public void setAge(String age) { this.age = age; } public void setName(String name){ this.name = name; } public String getName(){ return name; } //第一个构造方法 public anotherPerson (String name){ this.name = name; } //第二个构造方法 public anotherPerson(String name, String age){ this(name);//是用同一类中的其他构造方法 this.age = age; } public void ShowInfomation(){ System.out.println("name is "+ name +"and age is "+age); } } //子类 class Teacher extends anotherPerson{ String school = ""; public void setSchool(String school){ this.school = school; } public String getSchool(){ return school; } public Teacher(String name){ super(name); } //第一个构造方法 public Teacher(String age,String school){ super("babyDuncan",age);//使用父类的构造方法 this.school = school; } public Teacher(Str<em style="color:transparent">来源gao.dai.ma.com搞@代*码网</em>ing name,String age,String school){ this(age,school);//使用同一类的构造方法,而这一构造方法使用父类的构造方法 this.name = name; } //重写了父类的函数 public void ShowInfomation(){ System.out.println("name is "+ name +" and age is "+age+" and school is "+school); } } public class testTeacher { /** * 测试一下super和this */ public static void main(String[] args) { // TODO Auto-generated method stub anotherPerson person1 = new anotherPerson("babyDuncan"); anotherPerson person2 = new anotherPerson("babyDuncan","20"); Teacher teacher1 = new Teacher("babyDuncan"); Teacher teacher2 = new Teacher("20","JLU"); Teacher teacher3 = new Teacher("babyDuncan","20","JLU"); person1.ShowInfomation(); person2.ShowInfomation(); teacher1.ShowInfomation(); teacher2.ShowInfomation(); teacher3.ShowInfomation(); } } 

输出结果:

 name is babyDuncanand age is name is babyDuncanand age is 20 name is babyDuncan and age is and school is name is babyDuncan and age is 20 and school is JLU name is babyDuncan and age is 20 and school is JLU

以上就是java this与super的实例应用,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

以上就是详解Java使用super和this来重载构造方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解Java使用super和this来重载构造方法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址