Please help with code

relativly new to java, and this is for a class so I am looking for documenation being pointed in the right way than direct answers.

I have a superclass with 2 subclasses.

I am trying to switch an object name between one of the two different object types so that as my program runs it will run based off the object type.

In short my code to switch between the object types is:

if (...)

{

SubClass1 x =new SubClass1();

}

elseif (...)

{

SubClass2 x =new SubClass2();

}

When I do this I get an error down the line the first time I try to use x.Method1(): error: "Cannot Find Symbol - variable x"

Can you not declare an object inside an if statement?

I am coding in BlueJ and that is required by my class.

[1064 byte] By [colmtourque2a] at [2007-10-3 6:54:41]
# 1

When you declare a variable it only is available inside the block where it is declared.

if(...)

{

SubClass1 x = new SubClass1();

// x is available until the closing brace

} // x is now undefined.

else if (...)

{

SubClass2 x = new SubClass2();

// now a new and completely unrelated x is available

} // x is now undefined.

Perhaps what you want is:

SuperClass x = null;

if(...)

{

x = new SubClass1();

} else if (...)

{

x = new SubClass2();

}

// x is still available since it was declared before the if

Using a super class reference to a subclass object is a normal part of object oriented programming

BillKriegera at 2007-7-15 1:46:17 > top of Java-index,Desktop,Developing for the Desktop...