Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explain the syntax EditText editText = (EditText) findViewById(R.id.edit_message);

Tags:

java

android

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

in the line

EditText editText = (EditText) findViewById(R.id.edit_message);

EditText is class and editText is the instance we are creating. findViewById(R.id.edit_message) is method and R.id.edit_message is the argument we are passing

But I can not understand why there is thos (EditText) present? is it the call to constructor?

like image 670
Nikhil Avatar asked Dec 19 '22 18:12

Nikhil


2 Answers

It's explicit typecasting. findViewById() returns a View and the (EditText) explicitly typecasts it to an EditText (which is a subclass of View). This works since the object returned in fact is-a EditText, that is, an object of that class or one of its subclasses. If it wasn't, you would get ClassCastException.

Read more: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

like image 142
laalto Avatar answered Feb 01 '23 22:02

laalto


is it the call to constructor? 

No.

 EditText editText = (EditText) findViewById(R.id.edit_message);

in the above line (EditText) is for typecasting..

findViewById() which returns the View object.so we typecast it to EditText Object.

EditText is a sub class of View Class.

like image 24
kalyan pvs Avatar answered Feb 01 '23 23:02

kalyan pvs