When creating an object(or anything) in java, what is the difference between doing, for example,
Dog d = new Dog();
instead of doing
Dog d;
and then later, finishing it off(sometimes inside and at the beginning of a method) with
d = new Dog();
Wouldn't the first one be more simple and easier? Why do people do it the second way?
Think of the following scenario. Assume the constructor of Dog can throw an exception:
try {
Dog d = new Dog();
} catch(Exception ex) {
// treat exception
}
d.bark();
This won't compile because d is not visible outside the try block. What you need to do is this:
Dog d = null;
try {
d = new Dog();
} catch(Exception ex) {
// treat exception
}
if(d != null) d.bark();
And there are many other situations like this. For example, you might have an if-else block where d is initialized differently based on some condition:
Dog d = null;
if(/* condition */)
d = new Dog("Lassie");
} else {
d = new Dog("Sam");
}
d.bark();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With