virtual 和 abstract关键字
概述
在 Salesforce Apex 中,virtual 和 abstract 是两种用于定义类和方法行为的关键字。了解这两者的区别及其用途对类的继承和方法的重写有重要作用。下面详细解释这两个概念,并提供相关代码示例。
虚拟类 (Virtual Class) 和虚拟方法 (Virtual Method)
virtual 类:一个类被声明为 virtual 时,表示它可以被其他类继承。默认情况下,Apex 中的类是不可继承的,除非它们被标记为 virtual。这种类的目的是允许它的子类能够扩展它的功能。
virtual 方法:一个方法被声明为 virtual 时,表示这个方法可以被子类重写(override)。即使在父类中已经实现了该方法,子类也可以提供自己的实现方式。
抽象类 (Abstract Class) 和抽象方法 (Abstract Method)
abstract 类:一个类被声明为 abstract 时,表示这个类不能直接实例化,只能作为父类被继承。它通常包含一些未实现的方法(抽象方法),这些方法必须由子类来实现。abstract 类的目的是提供一个基础框架,供具体子类进行扩展。
abstract 方法:一个方法被声明为 abstract 时,表示该方法没有实现,子类必须提供该方法的具体实现。如果父类是 abstract 的,则可以包含 abstract 方法。
区别与应用
virtual 类和方法允许继承和重写,但可以被直接实例化。它们提供了默认实现,子类可以选择覆盖这些实现。
abstract 类和方法无法直接实例化,并且要求子类实现所有 abstract 方法。
示例代码
示例 1: virtual 类和方法
public virtual class Car {
public String make;
public String model;
public Integer year;
// 构造函数
public Car(String make, String model, Integer year) {
this.make = make;
this.model = model;
this.year = year;
}
// 虚拟方法,可以被子类重写
public virtual void displayInfo() {
System.debug('Make: ' + make);
System.debug('Model: ' + model);
System.debug('Year: ' + year);
}
}
// 子类 ElectricCar 继承 Car 类并重写 displayInfo 方法
public class ElectricCar extends Car {
public Integer batteryCapacity;
// 构造函数
public ElectricCar(String make, String model, Integer year, Integer batteryCapacity) {
super(make, model, year); // 调用父类构造函数
this.batteryCapacity = batteryCapacity;
}
// 重写父类的 displayInfo 方法
public override void displayInfo() {
super.displayInfo(); // 调用父类的 displayInfo 方法
System.debug('Battery Capacity: ' + batteryCapacity + ' kWh');
}
}
解释:
Car 类被声明为 virtual,允许 ElectricCar 类继承它。
Car 类的 displayInfo 方法被声明为 virtual,允许 ElectricCar 类重写它。
示例 2: abstract 类和方法
public abstract class Car {
public String make;
public String model;
public Integer year;
// 构造函数
public Car(String make, String model, Integer year) {
this.make = make;
this.model = model;
this.year = year;
}
// 抽象方法,子类必须实现
public abstract void displayInfo();
}
// 子类 ElectricCar 继承抽象类 Car 并实现 displayInfo 方法
public class ElectricCar extends Car {
public Integer batteryCapacity;
// 构造函数
public ElectricCar(String make, String model, Integer year, Integer batteryCapacity) {
super(make, model, year);
this.batteryCapacity = batteryCapacity;
}
// 实现父类的抽象方法
public override void displayInfo() {
System.debug('Make: ' + make);
System.debug('Model: ' + model);
System.debug('Year: ' + year);
System.debug('Battery Capacity: ' + batteryCapacity + ' kWh');
}
}
解释:
Car 类被声明为 abstract,它不能被实例化。它包含一个 abstract 方法 displayInfo,表示该方法没有实现。
ElectricCar 类必须实现 displayInfo 方法,否则它也必须声明为 abstract 类。
总结
1.virtual 类:可以被继承并实例化,父类方法可以被子类重写。
2.abstract 类:不能直接实例化,通常提供一些未实现的方法,要求子类提供具体实现。
3.virtual 方法:可以被子类重写,子类有选择是否重写父类方法的自由。
4.abstract 方法:强制要求子类实现该方法,父类不能提供默认实现。
如果你遇到“Car 类本身不是虚拟(virtual)或抽象(abstract)的,因此无法被继承”这样的错误,通常意味着父类没有被声明为 virtual 或 abstract,导致无法继承。通过将父类声明为 virtual 或 abstract,可以解决继承和重写的问题。