Acceleration in java

In Java, suppose I have 3 classes, C extends from B, which extends from A.

class X {
   interface A {}
   interface B extends A {}
   interface C extends B {}
   void f(A a) {}

   void test() {
      C c = new C()
      B b = (B) c;

      f(b);
   }
}

If I do something like this, as shown in the test()above:

C c = new C()
B b = (B) c;

f(b);

f()It receives bas type C, as C, and bthe two extend from A. I wanted to f()get bas a type b, not a type C.

Is there any way to make this increase?

+3
source share
9 answers

f() will always receive something typed as A (despite the fact that under the covers it is actually B or C and can be omitted accordingly).

You can define extra f () this way

f(B b);

and if necessary

f(C c);

. , . ( ), .

, . :

C c = new C()
B b = c;

f(b);

C B, C B.

+9

, , .

( c b) C, C, , , ; , , .

, ? , , .

+2

, f b B, C.

A C B A.

f f A A f A , C, C .

. , , , C, C. B, B, C.

"C" "B" , C.

?

+1

. "f b C"?

f b A, "A". b, C, C . Java ( ++), .

, , .

+1

, A f (A a), OO Java, . C A, , A.

0

, , A:

public void f(A a) {
  if (a.getClass() == A.class) {
    // ok, go on
  }
  else {
    System.err.println("The parameter is not of class A!");
  }
}

, , .

0

REFERENCE INSTANCE. C B, - - C - , . , / - . C ( , ). B B- , B.

0

The fact that your code has a reference to A does not mean that the object that it points to is also A. If it is a C, it remains C. The link in your source restricts the available methods in your source. Casting is necessary only because sometimes a method of a different type is needed, and we need to trick the compiler so that we can start using methods for cast types. Naturally, if an invalidation attempt is made, the cast may fail at runtime.

0
source
In upcasting and downcasting the  object first upcast then downcastenter
class A
{
}
class B extends A
{
}
Class M
{
  psvm(String ar[])
{

   A a1= new B();
   B b2=(B)a1;
}
0
source

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


All Articles