服务器之家

服务器之家 > 正文

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

时间:2020-12-19 14:01     来源/作者:babyduncan

详解Java使用superthis来重载构造方法

实例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//父类
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 {
 
  /**
   * 测试一下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();
  }
 
}

输出结果:

?
1
2
3
4
5
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的实例应用,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://babyduncan.iteye.com/blog/776559

标签:

相关文章

热门资讯

2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国 2021-05-08
返回顶部