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);
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