W
W
webmaster22018-09-01 13:20:53
Java
webmaster2, 2018-09-01 13:20:53

Type casting in Java?

Good afternoon!
Understanding type casting in Java. I write the following code:

public static void main( String[] args ) throws Exception {
        A a = new B();
        System.out.println(a.getClass().toString());
        ((B) a).testB();
    }

    static class A {
        public void testA() {
            System.out.println("A class, A method...");
        }
    }

    static class B extends A {
        public void testB() {
            System.out.println("B class, B method...");
        }
    }

The following is displayed on the console:
class algorithms.App$B
B class, B method...
And, in fact, the question is: why getClass() says that the variable a has type B, if you still need to cast the type to use the functionality of class B to B.
Thanks in advance for your reply!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D3lphi, 2018-09-01
@webartisan2

getClass() returns an object of type Class<T>, in fact, this object represents the type that any entity has. This method is executed at runtime .
Type checking is done at compile time .
The variable a has type A, so in order to work with this variable as an object of type B, you need to explicitly cast it to this type. You can’t just call a.testB() without casting, because for the compiler this object has type A (and there is no method with the testB() signature in it).
However, with reflection, you can call the method dynamically:

java.lang.reflect.Method method = a.getClass().getMethod("testB");
method.invoke(a);

But in this case, you lose compile-time type checking.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question