class P { public P(int i) { }; public P() { }; public void m() { }; public void m1() { }; } class Q extends P { public void m() { }; } class Z { public static void main(String[] args) { P p1 = new P(); P p2 = new Q(); Q q1 = new Q(); } }Note: In a class hierarchy, subclasses are written BELOW the classes they extend.
For example, if the following code is inserted at the end of the main method in class Z, then the comments following each method call explain exactly which method is called.
p1.m(); // calls m() defined in class P p2.m(); // calls m() defined in class Q q1.m(); // calls m() defined in class Q
For
example, P p2 = new Q(); is a legal assignment statement because
Q is a subclass of P.
class R extends P { public void m() { }; }And R r = new R(); we cannot say q1 = (Q)r; because R is neither the same as Q nor a subclass of Q.
For example, Q q2 = (Q)p2;, follows this rule because p2 was created as an instance of type Q, and q2 is of type Q. Another statement that follows this rule is p1 = (Q)p2;
Note:This type check is done at runtime. It depends on the type of the particular instance being cast when the code is executed.
For example, q1 = (Q)p1; will compile okay because the variable p1 is of type P which can be cast to Q. But when we try to run this statement, java notices that p1 refers to an instance of type P. Since P is not the same as Q or a subclass of Q, it gives a "ClassCastException" error.
Also note the difference between this rule and the previous rule. The statements P r = new R(); q1 = (Q)r; will compile because the variables have types that follow rule 3, but we will get a runtime error because the instance of the object referred to by r does not follow this rule.
There is a diagram to help you understand
rules 3 and 4.
For example, q1.m1(); follows this rule.
For example, we can define the following constructor for Q:
public Q(int j) { super(j); // calls the constructor in P }
For example, the following constructor for Q calls the constructor P().
public Q(int a) { // calls the constructor P(); System.out.println(a); }