Answer the question
In order to leave comments, you need to log in
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...");
}
}
Answer the question
In order to leave comments, you need to log in
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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question