bp01442
bp01442

Reputation: 69

Java can anyone explain why this keeps throwing an error?

Object Oriented programming

sorry for the lack of clarity.

our teacher gave us this example its a singleton and factory pattern program combined however when I run it in java it keeps telling me that the class fromExperian doesn't exist. I've retyped it word for word in eclipse and double checked for anything different it's one program all in the same file.

It looks like it can't find the classes even though they are in the same file?

page 1 page 2 page 3
page 4 page 5 page 6

Upvotes: 1

Views: 106

Answers (3)

pommes
pommes

Reputation: 181

Your code works for me. But only as long as it exists in the default package!

You have to use Class.forName(...) with the canonical class name. So as long as you are not in the default package your error occurs.

penCheck = (pen)Class.forName(s).newInstance();

leads to your error if your class does not lie in the default package.

penCheck = (pen)Class.forName(fromExperian.class.getCanonicalName()).newInstance();

instead will always work.

And yes it also works when fromExperian is abstract.

Upvotes: 2

IByrd
IByrd

Reputation: 177

I am not sure where your files are. Make sure all your .java files are in the proper spots. I don't know the details but when you get this kind of error I believe it's because the JVM can't find the .class file that the compiler was supposed to have made. When you compile it check your classpath and make sure everything is in the right packages and what not. Your single_factory_pattern.class or fromExperian.class is the culprit.

Upvotes: 0

xlecoustillier
xlecoustillier

Reputation: 16351

When you set the company to Experian, you then try to instantiate the fromExperian class. That can't happen, as fromExperian is abstract.

You'll have to make your fromExperian class concrete by removing the abstract keyword, or create at least a concrete class named (which name starts with "from") that extends fromExperian and set the company name accordingly.

Upvotes: 2

Related Questions