0

I have recently started with android devolopment in Java after learning the basics and I noticed a new way that objects were initialised. For example:

TextView t = (TextView) findViewById(R.id.textbox);

Here I would like to know what (TextView) means and why can't we initialise a object by a static method or the new keyword. Thank you!

Edit:

I would also like to know what happens when a superclass object is casted on a base class object (What propities are inherited)

Karan Gandhi
  • 303
  • 1
  • 2
  • 15
  • 2
    It is called type casting. You can get more information in basic Java tutorials :) – Pradeep Simha Jun 15 '20 at 10:54
  • So what exactly does `findViewById()` return – Karan Gandhi Jun 15 '20 at 10:56
  • That's a different question entirely and you can find the answer [in the docs](https://developer.android.com/reference/android/view/View#findViewById(int)). – Federico klez Culloca Jun 15 '20 at 10:59
  • 1
    `findViewById()` returns a widget that was already created and is in the view hierarchy. If this line is coming from an activity, then most likely the view hierarchy was set up by a `setContentView()` call sometime before this `findViewById()` call. – CommonsWare Jun 15 '20 at 10:59

1 Answers1

0
TextView t = (TextView) findViewById(R.id.textbox);

The statement findViewById(R.id.textbox) returns a View object from your xml layout that the Activity(or Fragment) is inflating, but the variable t needs a TextView object so you have to explicitly cast it as a TextView object with the (TextView) expression.

Why can't we initialise a object by a static method or the new keyword.

You can create a TextView object wih the new keyword like TextView t = new TextView(this) but then you have to dynamically place it into your Activity.

Vivek Singh
  • 1,142
  • 14
  • 32
  • So what happens to the properties of the `TextView` object when we cast a `View` objects in it? – Karan Gandhi Jun 15 '20 at 12:13
  • The TextView object retains its properties as well as all the properties from the Vew class, considering that the TextView class already inherits from the View class. – Vivek Singh Jun 15 '20 at 12:16