• Post Reply Bookmark Topic Watch Topic
  • New Topic

basic Java polymorphism error  RSS feed

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to write a basic one for polymorphism. Can somebody tell me what's wrong here.
When running it, it gives error:
A.java:4: error: cannot find symbol
a.doPrint();
^
symbol: method doPrint()
location: variable a of type A
1 error
 
Marshal
Posts: 4052
239
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A very similar discussion about the in's and out's of Polymorphism going on over here. Take a look and see if that answers your question.
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Colin Zheng wrote:I am trying to write a basic one for polymorphism. Can somebody tell me what's wrong here.
When running it, it gives error:
A.java:4: error: cannot find symbol
a.doPrint();
^
symbol: method doPrint()
location: variable a of type A
1 error


Polymorphism isn't just "figure out the actual object type at runtime, and call the correct method" -- which it actually does, and does well. You have to satisfy the compiler (at compile time) as well. To the compiler, the reference type is something that IS-A A, and you are calling a method that isn't available for the A type.

Henry
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should have a 'doPrint' method in your class A with the same signature as that present in Class B.(access modifier can be same or more restrictive in class A's doPrint).That would help to get rid of compile time error. At run-time, your class B's doPrint operation will be invoked. This concept is called overriding.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!