Java 这个用户定义的数据类型是如何铸造的?
应用Java语法,上述语句表示方法返回的值 findViewById更改为数据类型按钮,并存储在变量按钮单击中 我学爪哇语显然还不够!,而且从未遇到过类型转换用户定义的数据类型。Java 这个用户定义的数据类型是如何铸造的?,java,android,type-conversion,Java,Android,Type Conversion,应用Java语法,上述语句表示方法返回的值 findViewById更改为数据类型按钮,并存储在变量按钮单击中 我学爪哇语显然还不够!,而且从未遇到过类型转换用户定义的数据类型。 这是如何工作的?这是显式强制转换,因为Button类扩展了View类,View类是findViewById方法的返回类型。您应该使用显式转换进行下游转换,因为这是不安全的。您可以在Java中的任何对象之间使用显式转换,但是如果实际上不可能进行这种转换,您将在运行时获得ClassCastException。另一方面,隐式
这是如何工作的?这是显式强制转换,因为Button类扩展了View类,View类是findViewById方法的返回类型。您应该使用显式转换进行下游转换,因为这是不安全的。您可以在Java中的任何对象之间使用显式转换,但是如果实际上不可能进行这种转换,您将在运行时获得ClassCastException。另一方面,隐式强制转换总是安全的,因此不需要声明它。隐式转换是上游转换,例如从视图到对象。将@nikis响应放入代码中:
Button buttonClick = (Button) findViewById(R.id.button)
它的工作原理与任何其他铸件相同。不管是谁编写了这个类,这是因为Button扩展了从findViewById返回的视图
public class View extends Object {...}
public class Label extends View {...}
public class Button extends View {...}
public View findViewById(String id) {...}
//normal assignment
View v = findViewById(viewID);
//implicit casting to base class
Object o = findViewById(objectID);
//compile time error because the return might not be a Button
Button b = findViewById(buttonID);
//explicit cast forces compiler to treat the return as a Button
//if the return is not a Button, then ClassCastException is trown at runtime
Button bb = (Button)findViewById(buttonID);