how JVM takes decision about which methods to call,weather printS1(),printS2() methods of class P or class Q?
This is called dynamic method lookup. The method invoked depends on the type of the object (not the object refence) at runtime. For example, I have
P ref = new P();
ref.printS1();
the printS1 of P will be invoked. Continuing, if now I have
ref = new Q();
ref.printS1();
the printS1 of Q will be invoked. Note that the object reference ref is now referring to a different object. The object reference is not the same as the object it refers to. The object reference ref is of type P, while the type of the object it is referring to
at that point in time is an object of type Q. The object reference ref can still refer to an object of type Q, since, because of inheritance,
an object of type Q is also an object type P. (A cat is a mammal because cat is a subclass of mammal...)
This is called
polymorphism. It allows your code to be more flexible because you can invoke different implementations of a method while the application is already running.