Casting objects so that we use primitive data types

I have three classes A, AAand Top. A and AA expand the top.

Why this will not compile:

A a = new A();
AA aa = (AA)a;

but it will be:

float f = 4.3f;
int i = (int) f;
+4
source share
3 answers

Class Aand class AAare in the same hierarchy, but they are side by side, so they cannot be distinguished from each other.

Suppose a class has Abeen defined as follows:

public class A extends Top{

   public A() {

   }

   public void foo(int i) {
      System.out.println(i);
   }

}

And this class AAwas defined as follows:

public class AA extends Top {

   public AA() {

   }

   public void bar(String s) {

   }

}

Now let's theoretically imagine what would actually happen if you tried to apply Ato AA, and it worked:

A a = new A();
(AA) aa = (AA) a;

AA AA, Java :

aa.bar("hi!");

AA , BUT AA A, , , AA, bar("hi!").

( , , , .)

, Java AA bar("hi!"), AA , , AA bar.

+1

cast , . cast A, a.cast(B b).

public class A {
    public int i;
    public  A cast(B b){
        A a = new A();
        a.i=b.i;
        return a ;
     }
}

public class B {
    public int i=10;
}



public class Tester {
    public static void main(String[] args) {
        B b = new B();
        A a= new A();
        a=a.cast(b);
        System.out.println(a.i);
    }
}
0

Java - , , , . Java , , Widening Primitive Conversion ( ) Narrowing Primitive Conversion ( ), Java. , , int i = (int) f;, , Java Spec Java- . int a = (int) true, , boolean int.

, A a = (A) b, b , A sub-type A , :

Object b = c;
A a = (A) b;

, b Object, , Object root Java, b , type A, . b a A, , ClassCastException.

, A a = (A) b, , b A:

class A {}
class B {}

A b, , b A, Inconvertible types A a = (A) new B(). : ( Java).

0

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


All Articles