What is inheritance
继承是在已有类的基础上构建新的类,一个类继承已有类后,可以对被继承类中的属性和方法进行重用。继承是面向对象的另一个特性,可以最大限度地实现代码复用。
继承关系通常也称为 is kind of 关系
B is a kind of A means A is a general class and B is a special class.
在UML中,用三角形表示继承关系
在JAVA中,用extends 关键字实现
subClass and BaseClass
subClass
同一个包中:public protected default
不同包中: public protected
package Employee;
public class Employee {
public String id;
public String name;
public Employee(String id, String name) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return id;
}
public String getName() {
return name;
}
}
package Employee;
public class PartTimeEmployee extends Employee{
public double hourlyPay;
public PartTimeEmployee(String id, String name, double hourlyPay) {
super(id, name);
this.hourlyPay = hourlyPay;
}
public void setHourlyPay(double hourlyPay) {
this.hourlyPay = hourlyPay;
}
public double getHourlyPay(){
return hourlyPay;
}
public double calculateWeeklyPay(int hour){
return hour*hourlyPay;
}
}
package Employee;
import java.util.*;
public class PartTimeEmployeeTest {
public static void main(String args[]) {
String id, name;
double pay;
int hour;
Scanner sc = new Scanner(System.in);
id = sc.next();
name = sc.next();
pay = sc.nextDouble();
hour = sc.nextInt();
PartTimeEmployee emp = new PartTimeEmployee(id, name, pay);
System.out.print(emp.calculateWeeklyPay(hour));
}
}
方法重写
public class Employee {
public String getName() {
return name;
}
}
public class PartTimeEmployee extends Employee{
public String getName(){
System.out.print("PartTimeEmployee ");
return super.getName();
}
}
public class PartTimeEmployeeTest {
public static void main(String args[]) {
PartTimeEmployee emp = new PartTimeEmployee(id, name, pay);
System.out.print(emp.getName());
}
}
In:
1001 li 0.8 4
Out:
PartTimeEmployee li
3.2