-1

I am totally confused as to below code does upcast or downcast. If so how?

Is TextView a super class, I presume its a sub-type of View.

TextView textView = (TextView) findViewById(R.id.textView);
aminography
  • 21,986
  • 13
  • 70
  • 74
Yuvraj Mudaliar
  • 375
  • 5
  • 15
  • 1
    With buildgrade 3.0, you do not need cast this view. But TextView is a subview of View – Brian Hoang Dec 31 '18 at 07:33
  • Textview is a subview of view and view itself extends object. Take a look at this: https://developer.android.com/reference/android/widget/TextView – Umair Dec 31 '18 at 07:35

3 Answers3

2

In short, It's down casting.

This line :

findViewById(R.id.textView);

Will return a view, But what kind of view it is ? (Button,List, TextView, ..) Look at this example :

public abstract class Car{
    public abstract void power();
}

public class BMW extends Car{
    public void power(){
        System.out.println(2200);
    }
}

public class Benz extends Car{
    public void power(){
        System.out.println(2100);
    }
}

Creating an object of above classes (BMW,Benz)

BMW bmw = new BMW();
Benz benz = new Benz();

public class CarFactory{

    public void create(Car car){
        if(car instanceof Benz)
            Benz benz = (Benz) car;
        else 
            BMW bmw = (BMW) car ;
    }
}

Both of them (Benz, BMW) are explicit cast, like TextView.

I hope this helps you

Mohammadreza Khatami
  • 1,444
  • 2
  • 13
  • 27
1

its called DownCasting. you can understand deeply here

Mayur Dabhi
  • 3,607
  • 2
  • 14
  • 25
1
TextView textView = (TextView) findViewById(R.id.textView);

The code you have mentioned is downcasting. Because findViewByID returns a View Object and TextView is a child of a View class. When casting from parent to child is called Down Casting While castinrg from child to Parent is called Upcasting.

Note: When you casting up, you normally do not need to cast cause of implicit casting.

Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58