-2

And in java

    class Person{}
    class Student extends Person{}
    public class Test {
        public static void main(String[] args) {
            Person person = new Person();
            Student student = (Student)person;
        }
    }

There is a "Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to Student"

alert
  • 1
  • 3

2 Answers2

1

You are doing down casting

Below down casting is not allowed. Because person is not instance of Student or Student's subclass.

Student student = (Student)person;

Below down casting is ok. because the result of findview is instace of Button.

Button button = (Button)findViewById...

Refer this answer https://stackoverflow.com/a/23414798/5183999

Community
  • 1
  • 1
nshmura
  • 5,940
  • 3
  • 27
  • 46
0

If you want to simulate the case in Android with your example, it should be like this:

class Person{}
class Student extends Person{}

public class Test {
    public static void main(String[] args) {
        Person person = getPerson();
        Student student = (Student) person;
    }

    private Person getPerson() {
        return new Student();
    }
}

Which is perfectly OK.

This means the object that findViewById() returns, is actually a Button, but up-casted to View. Later you need to down-cast that to the Button.

Mousa
  • 2,190
  • 3
  • 21
  • 34
  • Where can I find something more about how findViewById() achieve? – alert Aug 14 '16 at 06:57
  • Check out `View` class [documentation](https://developer.android.com/reference/android/view/View.html). This method is simple, you just need to cast the return value to whatever view type you've used in the xml file. – Mousa Aug 14 '16 at 07:23