If i replace YYY s =new YYY();
XXX s =new YYY();
then why is it necessary to wrap the main method in try/catch block . The s.m() will call the method m from class YYY, which does not throw any exception.So it shouldn't be necessary to wrap it in a try/catch block.
The compiler only knows and cares about the reference type (which is fixed at compile time), not the object class (which can be determined at runtime).
That is, it only cares about XXX s, not about =new YYY(), and since XXX.m() is declared to throw Exception, you have to deal with it.
So, yes, is should be (and is) necessary to catch or declare Exception. Whenever the compiler or the runtime does X, and you find your self thinking, "It should be doing the opposite of X," it's time to reevaluate your assumptions.