Sending a child as a parent parameter

I came across this code:

public class B extends A
{....}

public class C extends A
{...
 public boolean f(A a)
   {...}
}
//driver
...
A y1=new B();
B y2=new B();
A z1=new C();
C z2=new C();
//1 System.out.println(z1.f(z2));
//2 y1.dosmth()==((B)(z1).dosmth());

Initially, I thought # 1 would be incorrect, because f can only get an object defined as A , but apparently it also works with an object that is a child of A (z2 is defined as C and is an object C). Does inheritance limit the use of methods to get arguments defined in the same way as in a method?

O # 2: I realized that casting is possible only if the object has some kind of inheritance relationship. those. I can not do (Animal)table. However, it seems to work here. Is it because B extends A, like C? Although it still looks like (Dog)cator something like that.

!

+4
2

!

A a , a A. C A, System.out.println(z1.f(z2)). :

A a = C()

f (z2) → f (a).

dosmth() B, C, №2 . , :

B C A, .

, A getMe(), B C getMe(), , getMe() B C.

, getMe() B C. , getMe() getMe(). getMe() getMe(), , , getMe() . getMe() B C, B C A getMe().

, , .

var1 = new Dog()

var2 = new Cat()

() var1.bark()// !

: " , , , !", , . , Animal. Animal bark(), , , . Animal to Dog, , Animal .

, !

+1
  • ,

  • Java - - Compile-Time. java.lang.ClassCastException , . , ", Java, , , , ! ."

0

Source: https://habr.com/ru/post/1628763/


All Articles