简体   繁体   English

在 Java 中使用抽象 class 的名称创建一个新的 object?

[英]Creating a new object in Java with the class name of an abstract class?

I'm working on some exam revision work and created an Employee abstract class and two other classes (AcademicEmployee and ProfessionalEmployee) which extend off of the Employee class.我正在进行一些考试修订工作,并创建了员工摘要 class 和其他两个类(AcademicEmployee 和 ProfessionalEmployee),它们从员工 class 延伸出来。

I have a public static void main set up in the Employee class to run these lines:我在 Employee class 中设置了一个公共 static void main 来运行这些行:

ProfessionalEmployee boss = new ProfessionalEmployee("The Big Man", 5000.0, null, 10);
AcademicEmployee e1 = new AcademicEmployee("Ryan", 1000.0, boss, 'A');

I know you can't instantiate an abstract class and the actual object getting created is whatever comes after the "new" keyword but why am I allowed to do this:我知道你不能实例化一个抽象的 class 而实际创建的 object 是在“new”关键字之后出现的,但为什么我允许这样做:

Employee boss = new ProfessionalEmployee("The Big Man", 5000.0, null, 10);

I'm thinking it works in the way of "Data type" then "Reference name" = new...我认为它以“数据类型”然后“参考名称”=新的方式工作......

but I'm just confused on why I'm allowed to set the data type to Employee.但我只是对为什么允许将数据类型设置为 Employee 感到困惑。 Sorry if this is a strange question, I'm just new to Java:)抱歉,如果这是一个奇怪的问题,我只是 Java 的新手 :)

This is a concept of Polymorphism in java.这是 java 中的多态性概念。 Since both of your class ProfessionalEmployee and AcademicEmployee extends Employee , both can be assigned to Employee reference object.由于您的 class ProfessionalEmployeeAcademicEmployee都扩展了Employee ,因此两者都可以分配给Employee参考 object。

Polymorphism allows you define one interface or class and have multiple implementations.多态性允许您定义一个接口或 class 并具有多个实现。

Your question reads,你的问题是,

Creating a new object in Java with the class name of an abstract class?在 Java 中使用抽象 class 的名称创建一个新的 object?

But where have you created a new object like that?但是您在哪里创建了这样的新 object? You have created two Object s as below,您已经创建了两个Object如下,

 new AcademicEmployee("Ryan", 1000.0, boss, 'A');

new ProfessionalEmployee("The Big Man", 5000.0, null, 10);

And, both AcademicEmployee and ProfessionalEmployee cannot be abstract which otherwise you will get a compile-time error.而且, AcademicEmployeeProfessionalEmployee都不能是abstract的,否则你会得到一个编译时错误。

Since AcademicEmployee and ProfessionalEmployee is an Employee (since you have extended/implemented it), you are allowed to assign!由于AcademicEmployeeProfessionalEmployeeEmployee (因为您已经扩展/实现了它),所以您可以分配!

This is explained in simple words here这在这里用简单的话解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM