Hello. When we change the type of an object, like this:
A b = (B) a What we finally get: an object of type A or an object of type B? Constant confusion.
Hello. When we change the type of an object, like this:
A b = (B) a What we finally get: an object of type A or an object of type B? Constant confusion.
This is called type casting. In fact, the type of an object cannot be changed, but you can bring it to a supertype or a subtype. Cast to type - this means that now an object can be treated as an instance of a reduced type.
For example, if you declare a collection
Collection collection = new ArrayList()
then you will have a collection variable in which you can call the add method (because it is declared in the Collection interface), but in the end you will call the add method of the ArrayList class (see about late binding and virtual methods). But you cannot call the get method. But not because you changed the type of the object, but because in the Collection interface the given method is not set, which means it is undersized through the collection variable.
Now somewhere in the code you perform the following operation:
List list = (List) collection; Notice that you still have one instance of ArrayList (there is one object in memory), but it is now referenced by two variables that are of different types: Collection and List .
By the way, all mentioned transformations are possible, because List is a supertype for ArrayList , and Collection is a supertype for List . If you tried to convert ArrayList to Set , for example, you would get an error (at the stage of compilation or execution, depending on the code).
B link1=new B(); A link2 = (A) link1; If we assume that "B extends A", then link1 will have type A and be able to call only methods of class A, but will refer to the memory area where B () is stored. Also, if methods are redefined in B, then they will be called ...
this happens because the descendant class is also the parent class at the same time. In memory, they are stored as
{{родитель}{потомок}} {{A}{B}{C}{...}}//при наследовании A<-B<-C<-... The type of an object does not change from the use of a casting operation !
If I remember correctly and if we assume that class B is a successor of class A, then it turns out that object b belongs to class A.
We get a type A reference to an object, and nothing happens to the object itself; it remains of the type, the constructor of which class it was created.
Source: https://ru.stackoverflow.com/questions/312412/
All Articles