简体   繁体   English

使用new()运算符创建对象是否是多态性?

[英]Is creating an Object using new() operator is polymorphism?

Recently I attended an interview and a question was asked to me 最近我参加了一次采访,问了一个问题

Is creating an Object using new() operator is polymorphism? 使用new()运算符创建对象是否是多态性?

For ex: 例如:

Employee e = new Employee();

Is this polymorphism? 这是多态吗? (Reply with yes and no and explain.) (回答是和否并解释。)

I was unable to think of the answer. 我想不出答案。

As what i have read about polymorphism is compile type and runtime. 正如我所读到的关于多态性的是编译类型和运行时。

Can anybody explain? 有人可以解释吗? Thanks. 谢谢。

If you assign a base class reference to a child class object then it is a form of polymorphism. 如果将基类引用分配给子类对象,则它是多态的一种形式。

Polymorphism, which etymologically means "many forms," is the ability to treat an object of any subclass of a base class as if it were an object of the base class. 多态性在词源上意为“许多形式”,是一种将基类的任何子类的对象视为基类的对象的能力。 A base class has, therefore, many forms: the base class itself, and any of its subclasses. 因此,基类具有多种形式:基类本身及其任何子类。

This is NOT an example of polymorphism 这不是多态的例子

Employee e = new Employee();

but assume if Empolyee is a class, which is extended from another class called Person then this will enable polymorphism by calling the methods of Employee at the run time: 但是假设Empolyee是一个类,该类是从另一个名为Person的类扩展的,则这将通过在运行时调用Employee的方法来启用多态性:

Person p = new Employee();

Read this article to learn more: 阅读本文以了解更多信息:

http://www.artima.com/objectsandjava/webuscript/PolymorphismInterfaces1.html http://www.artima.com/objectsandjava/webuscript/PolymorphismInterfaces1.html

According java polymorphism 根据Java多态性

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. 字典中的多态性定义是指生物学中的一种原理,其中生物或物种可以具有许多不同的形式或阶段。 This principle can also be applied to object-oriented programming and languages like the Java language. 该原理也可以应用于面向对象的编程和Java语言之类的语言。 Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. 一个类的子类可以定义自己的独特行为,但可以共享父类的某些相同功能。

Employee e = new Employee(); 

is not the example of polymorphism. 不是多态的例子。
But

Object emp = new Employee();  

is an example for polymorphism.Since here Subclass ( Employee ) defining its own unique behaviors and yet sharing some of the same functionality of the parent( Object ) class. 是多态的一个例子。从这里开始,子类( Employee )定义了自己的独特行为,并且共享了与parent( Object )类相同的功能。

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

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