Reputation: 6116
Normally, It is not possible to use one variable (one identifier) as two or more object in one scope. I mean the below program will not work:
public void HashMachine() {
ClassA MyObj;
//Some functions on MyObj here
ClassB MyObj;
//Some other functions on the new MyObj here.
}
But I want to know if is it possible to use a single variable as two different object in different situations as follow:
public void HashMachine(int ObjType) {
switch(ObjType){
case 1:
ClassA MyObj;
//Some functions here for this MyObj
break;
case 2:
ClassB MyObj;
//some other functions for this MyObj
break;
}
}
Unfortunately the above program is also wrong and I can't run it.
So, this is my question :
Can I use one identifier(one variable) for two different objects in one scope? (each one for a specific situation/condition).
Why I want to do this?
Upvotes: 1
Views: 65
Reputation: 141
I think what your are looking for is an union. However it doesn't exist in Java. I could find this link which I hope will be usefull for you http://lambda-the-ultimate.org/node/2694#comment-40453
I think in this way the program is shorter than the form that you must use different variables
Maybe it does, but what about readability ?
As I want to write a Java Card applet, and in the Java Cards, Garbage Collector in not present, it is better to have objects and variables.
I am not sure I understand correctly your sentence.
To conclude, I strongly recommend you not to add ambiguity to your code
Upvotes: 1
Reputation: 2109
Yes. You can do this. This is concept of abstraction. You can do like below
public interface MyInterface{...}
public class ClassA implements MyInterface {...}
public class ClassB implements MyInterface {...}
Then, you can refer to object of either class ClassA
or ClassB
by having a reference object of MyInterface
.
MyInterface MyObj;
switch(ObjType){
case 1:
MyObj = new ClassA();
//Some functions here
break;
case 2:
MyObj = new ClassB();
//some other functions
break;
}
Another option is provided by Das Louis in his example.
Upvotes: 1
Reputation: 140
You can't use the same name twice in the same scope. However, you can create new scope in your case statements within which you can use the name again. For example:
switch(ObjType)
{
case 1:
{
ClassA MyObj;
//some code
}
break;
case 2:
{
ClassB MyObj;
//some code
}
}
Here, ClassA MyObj
is out of scope by the time the program reacehs the second case statement, so ClassB MyObj
is legal.
Upvotes: 4