1) First of all, if TypeB's constructor is private, then you would get an error EARLIER - wherever you try to create a new instance of TypeB. This is unrelated to the question of when you can cast objectB to TypeA.
2) The key idea here is about compatible types for casting objects. Let's assume that objB has an actual type of TypeB. Then we can legally cast (TypeA) objB if TypeA is a superclass of TypeB (or a superclass of a superclass, etc), or TypeA is an interface that TypeB implements. This is sometimes called "upcasting", since we would be casting the object to a class or interface that is higher up (following the up arrows) in an UML diagram.
3) Another very important situation to consider, though, is that objB's declared type might be different from its actual type. For example, in JavaFX, BorderPane
is a subclass of Pane
which is a subclass of Region
which is a subclass of Parent
, which is a subclass of Node
. Suppose at some point we wrote:
Node obj = new BorderPane();
Then obj's actual type is BorderPane, even though the declared type is Node.
- Is it legal to cast
(BorderPane) obj
?
- Yes, because that is the obj variable's actual type.
- Is it legal to cast
(Parent) obj
?
- Yes, because the actual type of obj is
BorderPane
, and Parent
is an ancestor (superclass of superclass of superclass...) of BorderPane
.
- Is it legal to cast
(Object) obj
?
- Yes. Every class descends from
Object
.
- Is it legal to cast
(AnchorPane) obj
?
- No, because obj's real type is
BorderPane
, and a BorderPane
is not a descendant of AnchorPane
.
- Is it legal to cast
(Styleable) obj
?
- Yes, because
BorderPane
implements the Styleable
interface, and we can declare variables as interface types as well.
If you're still feeling confused, maybe try reading through this tutorial:
https://www.baeldung.com/java-type-casting