0

I'm not sure what this is even called, so it has been very difficult to search for an answer.

I am currently learning Java and Android development and have noticed a pattern where the type of object or variable being declared is repeated multiple times and I don't understand why.

For example:

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

Why does it have to be declared a type of EditText both before and after the assignment operator '='? Why isn't once enough? Why is this necessary?

I come from a ruby background and am having trouble wrapping my head around this.

2
  • It's called a cast Commented May 26, 2014 at 17:17
  • java is indeed very verbose when it comes to typing. Commented May 26, 2014 at 17:19

3 Answers 3

3

This is a result of something called Type Casting

EditText inherits from type View.

Since you want a variable of type EditText, but findViewById returns an object of type View, you have to cast the result of findViewById to EditText

To illustrate:

View uncasted = findViewById(R.id.edit_message);
EditText casted = (EditText)uncasted;
                  //casting happening on right side above
Sign up to request clarification or add additional context in comments.

Comments

1

The findViewById(...) is a method which will return a View Object (in your case a view called edit_message). Java however sees that you want an EditText Object on the one side

 EditText editText = ...

and that a View is returned on the other side

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

Java can't be sure that EditText is compatible with View (But you know that EditText is compatible with View because EditText is a child of the class View).

so to convince Java that your "edit_message" is actually an EditText Object, you have to cast it explicitly by adding (EditText) before the returning method findViewById(R.id.edit_message);

Afterwards your variable editText is a full blown EditText Object even when it came from a View.

Comments

1

If you look at the source code.

1883    public View findViewById(int id) {
1884        return getWindow().findViewById(id);
1885    }
1886

The return type is View. Since its a EditText object you cast it to EditText.

 EditText editText = (EditText) findViewById(R.id.edit_message);
 // this (EditText) is explicit casting

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.