abstract关键字的使用
-
1.abstract:抽象的
-
2.abstract可以用来修饰的结构:类、方法
-
3.abstract修饰类:抽象类
>此类不能实例化
>抽象类中一定有构造器,便于子类实例化的时候调用
>开发中,都会提供抽象类的子类,让子类对象实例化完成相关操作 -
4.abstract修饰方法:抽象方法
>抽象方法只有方法的声明,没有方法体
>包含抽象方法的类,一定是一个抽象类。抽象类中可以没有抽象方法。
>若子类重写父类中的所有的抽象方法后,次子类方可实例化
>若没有重写父类中的所有的抽象方法,则子类必须是一个抽象类
public class AbstractTest {
public static void main(String[] args) {
//一旦Person类抽象了,就不可以实例化
// Person p1 = new Person();
// p1.eat();
}
}
abstract class Creature{
public abstract void breath();
}
abstract class Person extends Creature{
String name;
int age;
public Person(){
}
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void eat(){
System.out.println("吃饭");
}
//抽象方法
public abstract void eat1();
public void walk(){
System.out.println("走路");
}
}
//父类中存在抽象方法时,子类的处理方式
//方式一
class Student extends Person{
public Student(String name, int age){
super(name, age);
}
//不重写所有抽象方法会报错
public void eat1(){
System.out.println("重写后的eat1()方法");
}
@Override
public void breath() {
System.out.println("重写的抽象方法");
}
}
//方式二
abstract class Student1 extends Person{
public Student1(String name, int age){
super(name, age);
}
// public void eat1(){
// System.out.println("重写后的eat1()方法");
// }
}
练习
- 编写一个Employee类,声明为抽象类,包含以下三个属性
- name,id,salary
- 提供必要的构造器和抽象方法:work()
public abstract class Employee {
private String name;
private int id;
private double salary;
public Employee(){
super();
}
public Employee(String name, int id, double salary) {
super();
this.name = name;
this.id = id;
this.salary = salary;
}
public abstract void work();
}
public class CommonEmployee extends Employee{
@Override
public void work() {
System.out.println("员工在一线车间生产商品");
}
}
public class Manager extends Employee{
private double bonus;//奖金
public Manager(double bonus){
super();
this.bonus = bonus;
}
public Manager(String name, int id, double salary, double bonus) {
super(name, id, salary);
this.bonus = bonus;
}
@Override
public void work() {
System.out.println("管理员工,提供公式运行的效率");
}
}
public class EmployeeTest {
public static void main(String[] args) {
// Manager manager = new Manager("kobi", 1001, 5000, 50000);
Employee manager = new Manager("kobi", 1001, 5000, 50000);//多态
manager.work();
CommonEmployee commonEmployee = new CommonEmployee();
commonEmployee.work();
}
}
练习
抽象类的应用:模板方法的设计模式
- 计算某个模块运行时间
public class TemplateTest {
public static void main(String[] args) {
SubTemplate t = new SubTemplate();
t.spendTime();
}
}
abstract class Template{
//计算某段代码所需要花费的时间
public void spendTime(){
long start = System.currentTimeMillis();
code();//不确定部分
long end = System.currentTimeMillis();
System.out.println("code花费的时间:" + (end - start));
}
public abstract void code();
}
class SubTemplate extends Template{
@Override
public void code() {
for(int i = 0; i <= 100000; i++){
boolean isFlag = true;
for(int j = 2; j <= Math.sqrt(i); j++){
if(i % j == 0){
isFlag = false;
break;
}
}
if(isFlag){
System.out.println(i);
}
}
}
}