java中抽象类继承抽象类_Java中的抽象类用示例解释

java中抽象类继承抽象类

Abstract classes are classes declared with abstract. They can be subclassed or extended, but cannot be instantiated. You can think of them as a class version of interfaces, or as an interface with actual code attached to the methods.

抽象类是用abstract声明的类。 它们可以被子类化或扩展,但是不能被实例化。 您可以将它们视为接口的类版本 ,或与方法附带实际代码的接口。

For example, say you have a class Vehicle which defines the basic functionality (methods) and components (object variables) that vehicles have in common.

例如,假设您有一个Vehicle类,它定义了Vehicle共有的基本功能(方法)和组件(对象变量)。

You cannot create an object of Vehicle because a vehicle is itself an abstract, general concept. Vehicles have wheels and motors, but the number of wheels and the size of motors can differ greatly.

您无法创建Vehicle对象,因为Vehicle本身就是一个抽象的通用概念。 车辆具有车轮和电动机,但是车轮的数量和电动机的尺寸可能相差很大。

You can, however, extend the functionality of the vehicle class to create a Car or a Motorcycle:

但是,您可以扩展Vehicle类的功能来创建CarMotorcycle

abstract class Vehicle
{
  //variable that is used to declare the no. of wheels in a vehicle
  private int wheels;
  
  //Variable to define the type of motor used
  private Motor motor;
  
  //an abstract method that only declares, but does not define the start 
  //functionality because each vehicle uses a different starting mechanism
  abstract void start();
}

public class Car extends Vehicle
{
  ...
}

public class Motorcycle extends Vehicle
{
  ...
}

Remember, you cannot instantiate a Vehicle anywhere in your program – instead, you can use the Car and Motorcycle classes you declared earlier and create instances of those:

请记住,您不能在程序中的任何地方实例化Vehicle ,而是可以使用之前声明的CarMotorcycle类并创建这些实例:

Vehicle newVehicle = new Vehicle();    // Invalid
Vehicle car = new Car();  // valid
Vehicle mBike = new Motorcycle();  // valid

Car carObj = new Car();  // valid
Motorcycle mBikeObj = new Motorcycle();  // valid

更多信息: (More information:)

翻译自: https://www.freecodecamp.org/news/abstract-classes-in-java-explained-with-examples/

java中抽象类继承抽象类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值