继承 --inheritance

1、继承:用父类定义子类,被继承的类称为父类,在父类的基础上新定义的类称为子类。

  • 子类继承父类的数据域和方法,但无法访问private数据成员,也无法重写private方法
  • 子类不继承父类的构造器,因此子类构造器必须用super(父类型引用)调用父类构造器,如果子类构造器不显式调用父类构造器,则编译器默认调用父类的无参构造器,若父类没有定义无参构造器,则子类构造器必须显式调用父类构造器。
  • 子类重写但不覆盖父类的public static数据域和方法,重写且覆盖父类的非static数据域和方法,子类需用super调用被屏蔽的父类数据域和方法。
  • Java不允许多继承
  • Object是所有类的父类,Object类型引用作为方法形参时,作用类似void*指针
/* 父类 */
public class Employee {
	
	private static int numberOfEmployee=0;
	private String name;
	protected double salary;
	
	public Employee(String name, double salary) {
		this.name = name;
		this.salary = salary;
		numberOfEmployee++;
	}
	public double getSalary() {
		return salary;
	}
	public double getIncome() {
		return salary;
	}
	public String getName() {
		return name;
	}
	public void SetSalary(double salary) {
		this.salary = salary;
	}
	public static int getNumberOfEmployee() {
		return numberOfEmployee;
	}
}

/* 子类 */
public class Manager extends Employee{
	private static int numberOfEmployee=0;
	private double bonus;
	public Manager(String name, double salary, double bonus) {
		/*子类不继承父类的构造方法,需要用super(父类型引用)调用父类构造方法 */
		super(name,salary);
		this.bonus = bonus;
		numberOfEmployee++;
	}
	
	/* 子类重写并覆盖父类的getIncome方法
	   * 父类的getIncome在子类会被屏蔽,需要用super调用
	 */
	public double getIncome() { 
		return super.getIncome()+bonus;
	}
	
	
	public double getBonus() {
		return bonus;
	}
	public void setBonus(double bonus) {
		this.bonus = bonus;
	}
	
	/* 子类重写父类的static方法,但不覆盖 */
	public static int getNumberOfEmployee() {
		return numberOfEmployee;
	}
}

2、动态绑定和转换
动态绑定:用父类型引用变量引用父类或子类实例,运行时根据变量实际引用的对象决定调用哪个方法。
向上转换:子类型引用赋值给父类型引用,安全,直接=赋值
向下转换:父类型引用赋值给子类型引用,不安全,需要强制转换+instanceof判定

public class MainTest{
  public static void main(String[] args) {
		Employee employee1 = new Employee("li",8000);
		/* 向上转换 */
		Employee employee2 = new Manager("wang",12000,3000);
		
		printBonus(employee1);  // 输出:li is general staff and has no bonus
		printBonus(employee2); //输出:wang is manager and he has bonus for 3000.0
	}
	public static void printBonus(Employee employee) {
		/* 判断子类对象要在父类对象之前,因为子类对象也是父类对象,反之则不成立   */
		if(employee instanceof Manager) {
			/* 向下强制转换 */
			System.out.println(employee.getName() +" is manager and he has bonus for "+((Manager)employee).getBonus());
		}
		else if(employee instanceof Employee) {
			System.out.println(employee.getName() +" is general staff and has no bonus");
		}
		
	}
}

3、final --禁止继承

  • final修饰数据成员,表示常量;
  • final修饰类,表示该类不能被继承;
  • final修饰方法,表示该方法不能被重写。

4、abstract --抽象类
用abstract修饰的类称为抽象类,抽象类不能new实例化,抽象类不一定含抽象方法,但有抽象方法的类一定时抽象类。

public abstract class Person {
   public abstract String getDescription();
}

你可能感兴趣的:(java入门)