Reputation: 71
I have a custom class Bus
with field int number
. The constructor therefore takes an int
when a new object is created.
class Bus {
int number;
Bus(int n) {
number = n;
}
}
There are a few objects created using the constructor seen above.
Bus bus = new Bus(21);
and so on.
Now I wish to change datatype to String
instead of int
.
If I simply change the datatype in Bus
class, I'll have to change all the objects I've already created which will be a lot of work if there are hundreds of objects.
I wish to know if there is any easier and smarter way to make these changes and avoid a lot of work. Or is there a better way to implement the class so that such changes would be easy to make?
Thanks!
Upvotes: 0
Views: 195
Reputation: 737
As you are ok to change the datatype, simply convert in same constructor.
class Bus {
String number;
Bus(int n) {
number = String.valueOf(n);
}
}
Upvotes: 0
Reputation: 11100
You can chose an object Higher in the object hierarchy than both int and string, for example object. You can then manipulate that object as you will in each method.
public class HelloWorld{
public Object n;
public HelloWorld(Object n){
this.n = n;
}
public static void main(String []args){
System.out.println("Hello World");
HelloWorld magic = new HelloWorld(23);
System.out.print(magic.n);System.out.print("\n");
}
}
Honestly an O O Design professional would bite my head off... prints::
HelloWorld
23
Upvotes: 0
Reputation: 17534
Just convert the int in the constructor.
class Bus {
String number;
Bus(int n) {
this(Integer.toString(n));
}
Bus(String n) {
number = n;
}
}
Upvotes: 1
Reputation: 2968
You can add one another constructor in Bus class and keep the existing one:
String number;
Bus(int n) {
this( String.valueof(n) ); // or do other thing, as you need
}
Bus(String n) {
number = n;
}
But may be it is not a good idea. If you can, you should remove the old constructor and do a complete refactor for each existing calls. Doing that, you avoid maintaining code which is not used anymore. If you can't do this, consider keeping the previous constructor and using @deprecated annotation to keep in mind to not use it anymore.
Upvotes: 1