简体   繁体   English

Android - 为什么对象被转换为类?

[英]Android - Why are objects casted to Classes?

I see this quite a lot, 我看到了很多,

A method which returns an object, ie 一种返回对象的方法,即

public Object getGroup(int groupPosition) 
{       
    return groups.get(groupPosition);
}

Then when this function is called, the returned object is casted to a certain class, ie 然后,当调用此函数时,返回的对象被转换为某个类,即

ExpandListGroup group = (ExpandListGroup) getGroup (groupPosition);

It seems to be the case that if a plain object is returned, you know the class of that object (TestClass) and you want to set a predeclared object (X) to that returned object (Y), you need to cast the corresponding class in the form of.. 似乎是这样的情况:如果返回一个普通对象,你知道该对象的类(TestClass)并且你想要为那个返回的对象(Y)设置一个预先声明的对象(X),你需要转换相应的类以......的形式

TestClass X = (TestClass) returnsY();

Is this correct? 这个对吗? Is there any other deeper meaning / consequence of casting an object as a class? 将对象作为一个类投射还有其他更深层次的意义/后果吗?

Cheers 干杯

All references needs to hold objects of same type as reference or its subtypes. 所有引用都需要保存与引用或其子类型相同类型的对象。 Since compiler knows only that getGroup returns Object it can't let Object to be assigned to TestClass reference (Object may not have implemented all methods that TestClass have). 由于编译器只知道getGroup返回Object ,因此不能将Object分配给TestClass引用(Object可能没有实现TestClass所有的所有方法)。 To solve that problem you need to explicitly tell compiler that object returned by getGroup is also TestClass class by casting it. 要解决这个问题,您需要明确告诉编译器getGroup返回的对象也是TestClass类,通过强制转换它。

That is done to be able to invoke TestClass's methods. 这样做是为了能够调用TestClass的方法。 But if there is not any previous check (to see that the object is really an instance of TestClass), you'll get a ClassCast exception 但是如果没有任何先前的检查(看到该对象实际上是TestClass的一个实例),你将得到一个ClassCast异常

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

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