-2

Not sure if the question makes sense, but basically what I'm trying to do is this

Object obj = new Object();
BankAccount s = (BankAccount) obj;
System.out.println(s instanceof BankAccount);

I want this to return true, but it throws me a class cast exception error. Why can I not cast BankAccount to Object? Is it because BankAccount is automatically a subclass of Object?

zzzzz
  • 87
  • 6
  • class cast exception questions have been answered before. https://stackoverflow.com/questions/3092796/classcastexception – Ali Tahir Sep 24 '20 at 03:57

2 Answers2

3

The type cast is telling the compiler "you think this obj has type Object, but trust me, it is actually a BankAccount". But you were lying about that, because it wasn't. The instance was only an Object.

The following would work:

Object obj = new BankAccount();
BankAccount s = (BankAccount) obj;
System.out.println(s instanceof BankAccount);
Henry
  • 42,982
  • 7
  • 68
  • 84
1

In addition to Henry's comment who explained that you could do the following:

Object obj = new BankAccount();
BankAccount s = (BankAccount) obj;
System.out.println(s instanceof BankAccount);

You should always keep in mind that variables are some kind of remote control.

The first line uses a Object remote control to control a BankAccount. This is possible because everything is an Object... this means you can use this remote control to control all objects. But you will also see that this control only supports operations that are defined in the Object class which means all Objects have.

The second line at the right side of the equation states that the referenced Object is actually a BankAccount. On the left side of the equation you force to create a new remote control that is able to control BankAccount objects.

MrBrightside
  • 119
  • 1
  • 9