详解Java使用super和this来重载构造方法实例代码://父类 class anotherPerson{ String name = ""; String age = ""; public String getAge()
详解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(String 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 { 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(); } }
--结束END--
本文标题: 详解Java使用super和this来重载构造方法
本文链接: https://www.lsjlt.com/news/224064.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0