Cooli Cooli - 1 year ago 48
Java Question

Creating objects in Java using the "Object" keyword

I have just started learning java and I have two basics questions.
My main() looks like this:

public class Main {
public static void main(String[] args) {
Storage<BankAccount> aStorage = new Storage<BankAccount>();
Storage<String> sStorage = new Storage<String>();

Class baCls = BankAccount.class;
try {
Object myAccount = baCls.newInstance();
aStorage.setValue( myAccount );
myAccount.deposit( 15 );
catch ( InstantiationException e ) {
catch ( IllegalAccessException e ) {

Why do I get these errors:

  • The method deposit(int) is undefined for the type Object

  • The method setValue(BankAccount) in the type Storage is not applicable for the arguments (Object).

After that I tried to replace:

Object myAccount = baCls.newInstance();


BankAccount myAccount = baCls.newInstance();

But then I am getting this error:

  • Type mismatch: cannot convert from Object to BankAccount

I know that the right way would be:

BankAccount myAccount = (BankAccount) baCls.newInstance();

But I am not really sure that I understand why...
I tried to read about it from a various sources so I have a few theories, but I still cannot wrap my head around this properly.
Can someone please help me understand?

Sorry for posting such a basic question.

Answer Source

Doing BankAccount myAccount = baCls.newInstance() invokes reflection to create a new object. Class is generic, but you have not specified the generic type. If you do Class<BankAccount> baCls = BankAccount.class then you shouldn't need to cast.

Java is strongly typed. By declaring an object as object you're saying to the language that this object is just an object: that is it only has the methods and fields found on ALL objects, and nothing more.

By specifying the type, you tell Java what methods and fields you can access, which is why when you write BankAccount myAccount, it allows you to call functions on it.

But baCls.newInstance() creates a new instance of whatever class baCls is. It doesn't know what type of class it is creating since it's a method on the Class class (confusing) itself, so you have to tell Java what class you expect it to return via casting: BankAccount myAccount = (BankAccount) baCls.newInstance();

However, the bigger question is why you are using newInstance in the first place. Is it possible to do:

BankAccount myAccount = new BankAccount();

Reflection is a little advanced for a beginner.