Java中的继承为单继承,即一个子类只能继承一个超类,但可以实现多个接口。超类是所有子类的公共属性及方法的集合,子类是超类的特殊化。其语法为:
[ClassModifire] class ClassName extends SuperClassName{
//类体
}
从外部来看,子类对象应该包括和超类相同的接口,但可以具有更多的方法;从内部来看,子类对象应该包含超类的所有变量和方法。
例:经理类(Manager)继承雇员类(Employee),雇员类继承Person类
public class Person{
public String Name;
public String getName(){
return Name;
}
}
public class Employee extends Person{
public int employeeNumber;
public int getEmployeeNumber(){
return employeeNumber;
}
}
public class Manager extends Employee{
public String responsibilities;
public String getResponsibilities(){
return responsibilities;
}
}
public class Exam4_2Test{
public static void main(String[] args){
Employee li = new Employee();
li.Name = "Li Ming";
li.employeeNumber = 123456;
System.out.println(li.getName());
System.out.println(li.getEmployeeNumber());
Manager he = new Manager();
he.Name = "He Xia";
he.employeeNumber = 543469;
he.responsibilities = "Internet Project";
System.out.println(he.getName());
System.out.println(he.getEmployeeNumber());
System.out.println(he.getResponsibilites());
}
}
//运行结果
Li Ming
123456
He Xia
543469
Interner Project
子类不能直接访问从超类继承的私有属性及方法,但可以使用公有及保护方法进行访问。
public class B{
public int a = 10;
private int b = 20;
protected int c = 30;
public int getB(){
return b;
}
}
public class A extends B{
public int d;
public void tryVariables(){
System.out.println(a); //ok
System.out.println(b); //fail
System.out.println(getB());//ok
System.out.println(c); //ok
}
}