• Post Reply Bookmark Topic Watch Topic
  • New Topic

Overriding  RSS feed

 
Athira Vineeth
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have two class A and B, where B extends A.



Main class



In this case it will print" Inside B:Print Me"
That means Object a of reference ClassA has access to the method defined inside ClassB.

But if i call a.printMy();then it is showing compilation error.
Why so?

Thanks in Advance
Athira
 
Walter Ho
Greenhorn
Posts: 22
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're missing a basic concept here.Suggest you read more on inheritance and
casting.
 
Micheal Quai
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"ClassA a=new ClassB(); "

1.a refer to Class A . there is a printME in ClassA.
2.then you "new " ClassB() to a .and ClassB() override the printME
3.a can not see the classB()

my english is so poor.
i hope that can help you .
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think your third line, Micheal Quai, is mistaken. It is not that you can’t see ClassB, but more that you can see it. The object is an instance of ClassB, so the ClassB version of the method is used.
 
Micheal Quai
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:I think your third line, Micheal Quai, is mistaken. It is not that you can’t see ClassB, but more that you can see it. The object is an instance of ClassB, so the ClassB version of the method is used.


i still don't understand why the printMY() method can't not be use.by "a"?
 
Manuel Petermann
Ranch Hand
Posts: 177
Hibernate Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lets make it a little more clear.


In this case you are assigning a new Tiger to an Animal variable.
This is possible because your Tiger is an Animal.

Problem now is, that an Animal cannot roar. A Tiger can.
The variable a just knows about the things defined in the Animal class.
If the above example would work, what do you suggest java should do when you type:
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Athira Vineeth wrote:But if i call a.printMy();then it is showing compilation error.
Why so?

And just to add to what Manuel said: Java uses the compile-time type to determine what methods can be 'seen', but the runtime type to determine which version of a method to run. This is what allows polymorphic behavior (check the tutorials).

HIH

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!