Reputation: 838
I am confused about polymorhism concept. Please can anyone help me out. Here is a simple code
class A {
int i=2;
void display() {
System.out.println("display method of A");
}
}
class B extends A {
int i=1;
void display() {
System.out.println("display method of B");
}
}
public class M {
public static void main(String[] arg) {
A a=new A();
System.out.println(a.i);
a.display();
a=new B();
System.out.println(a.i);
a.display();
}
}
O/p: 2 display method of A 2 display method of B
understood part: Reference variable 'a' of type 'A' is declared first and it refers to object of 'A'. When program prints 'a.i' it prints A's variable 'i' and when display is invoked as a.display() it calls Class A's display. Its fine till here
Problem part: Now when i assign reference variable 'a' object of type B and print a.i , it still prints 'i' value from class A(i.e 2). But when I call display function as a.display(), it calls display of method 'B'
My research: Whenever we access a member variable using reference variable then type of reference variable is checked for accessing it. While when we invoke method using reference variable object type is evaluated at run time (I think this is called as polymorphism) and depending on object type particular method is called
Am I right or there is some other concept involved? And I would also like to know what is polymorphism in detail and its application. And I will be greatfull if you would recommend me some books on basic concepts of OOP and java
Upvotes: 3
Views: 371
Reputation: 14709
You have a misunderstanding of what you should be doing in inheritance. extends
is a reserved word that was wisely chosen. The point of B extending A is to say that B is a subset of A with additional attributes. You're not supposed to redefine i
in B; A should be handling i
. By redefining i
in a subclass, you're hiding the superclass' field i
(this is true even if i
refers to different variable types).
A a=new A();
a.display();
System.out.println(a.i); //2 , since the i field in A is initialized to 2
a=new B();
a.display();
System.out.println(a.i); //2, since the i field in A is initialized to 2
If instead you redefined display()
in A
, B
to be:
void display()
{
System.out.println("Display method A/B: " + i);
}
A a=new A();
a.display(); //Display method of A: 2 , since the i field in A is initialized to 2
a=new B();
a.display(); //Display method of B: 1, since the i field in B is initialized to 1
I think that oracle does a pretty good job in their tutorial on polymorphism, but it may be helpful to start with inheritance.
Upvotes: 0
Reputation: 51721
That's because Polymorphism only applies to instance methods not fields. Hence, a.i
(where a
is of type A
) would always print 2
irrespective of whether it points to a sub-class object B
or not.
Upvotes: 2