8.10 方法重写/覆盖(override)

8.10.1 基本介绍

子类方法的返回类型和父类方法返回类型一样, 或者是父类返回类型的子类
比如 父类 返回类型是 Object , 子类方法返回类型是 String

 细节: 子类方法不能缩小父类方法的访问权限  public > protected > 默认>private

8.10.3 注意事项和使用细节

 8.10.4 课堂练习

方法的重写和重载做一个比较
1) 编写一个 Person 类,包括属性 /private name、 age ),构造器、方法 say( 返回自我介绍的字符串)。
2) 编写一个 Student 类,继承 Person 类,增加 id score 属性 /private ,以及构造器,定义 say 方法 ( 返回自我介绍的信息 )
3) main , 分别创建 Person Student 对象,调用 say 方法输出自我介绍
public class Person { 
private String name; 
private int age; 
public Person(String name, int age) { 
this.name = name; 
this.age = age; 
}
public String say() { 
return "name=" + name + " age=" + age; 
}
public String getName() { 
return name; 
}
public void setName(String name) { 
this.name = name; 
}
public int getAge() { 
return age; 
}
public void setAge(int age) {
this.age = age; 
} 
}
//编写一个 Student 类,继承 Person 类,增加 id、score 属性/private,以及构造器,定义 say 方法(返回自我介绍的信息)。 
public class Student extends Person{ 
private int id; 
private double score;
public Student(String name, int age, int id, double score) { 
super(name, age);//这里会调用父类构造器 
this.id = id; 
this.score = score; 
}
//say 
public String say() { 
//这里体现 super 的一个好处,代码复用. 
return super.say() + " id=" + id + " score=" + score; 
}
public int getId() { 
return id; 
}
public void setId(int id) {
this.id = id; 
}
public double getScore() { 
return score; 
}
public void setScore(double score) { 
this.score = score; 
} 
}
public class OverrideExercise { 
public static void main(String[] args) { 
//在 main 中,分别创建 Person 和 Student 对象,调用 say 方法输出自我介绍 
Person jack = new Person("jack", 10); 
System.out.println(jack.say()); 
Student smith = new Student("smith", 20, 123456, 99.8); 
System.out.println(smith.say()); 
} 
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值