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類的功能來創建Car
或Motorcycle
:
abstract class Vehicle
{//variable that is used to declare the no. of wheels in a vehicleprivate int wheels;//Variable to define the type of motor usedprivate Motor motor;//an abstract method that only declares, but does not define the start //functionality because each vehicle uses a different starting mechanismabstract 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
,而是可以使用之前聲明的Car
和Motorcycle
類并創建這些實例:
Vehicle newVehicle = new Vehicle(); // Invalid
Vehicle car = new Car(); // valid
Vehicle mBike = new Motorcycle(); // validCar carObj = new Car(); // valid
Motorcycle mBikeObj = new Motorcycle(); // valid
更多信息: (More information:)
Learn Functional Programming in Java - Full Course
學習Java函數式編程-完整課程
Getters and Setters in Java Explained
Java中的Getter和Setters解釋了
Inheritance in Java Explained
Java繼承說明
翻譯自: https://www.freecodecamp.org/news/abstract-classes-in-java-explained-with-examples/
java中抽象類繼承抽象類