-6

有人可以向我解释如何实现这些类型的代码并解释这三者之间的区别是什么?我正在用java编码。

4

3 回答 3

1

I'm goign to take a shot at it because I recently tried to understand those and this is a good way to see if I did :) because If you can't explain something you haven't really understood it :)

Casting is fairly simple. It means to pretty much convert a value or object of a certain type to a different type. This way you can for example turn a float into an integer

float y = 7.0
int x = (int) y

x will now be 7. Of course you can't simply cast any type to any other type. There are limitations which you should search for on google - i could never cover all of them.

Polymorphism sounds similar but is actually something else. As I understand it it means that certain objects can be of multiple types. For example of you have a class that extends another class any instance of the parent class can also be of the type of the derived class.

class Base {...} 
class Derived extends Base {...} 

Base obj1 = new Base();
Derived obj2 = new Derived();

obj1 = obj2;

Over the course of this snippet obj1 will have been an instance of Base first but then it will be an instance of Derived which is a class derived from base. This is possible because instances of derived classes contain an "inner object" (i don't know the official name) of the base class. When you cast the Base instance to an instance of Derived you will actually get this "inner object"

Hope this helps

于 2013-08-08T07:29:33.367 回答
0

请参阅 Oracle 的文档:http: //docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html

http://docs.oracle.com/javase/tutorial/java/IandI/index.html

于 2013-08-08T07:26:10.790 回答
0

真正的多态性(即多重继承)在 Java 中不可用。但是,您可以使用“接口”获得一个很好的近似值,尽管您的类需要实现接口提供的所有功能(链接到 Java 接口)。

您还可以在类上使用委托的 setter/getter 来模拟多重继承。这可能很复杂,但它也可以给你多重继承的效果。

这篇 Stack Overflow 帖子详细讨论了这个主题。

于 2013-08-08T07:34:10.143 回答