• Post Reply Bookmark Topic Watch Topic
  • New Topic

polymorphism in overriding methods  RSS feed

 
mohammad shaid
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hello friends.i am trying to solve a polymorphic problem which i came across in K&B5 page 109; its my own written code and i have added constructors to this code.this code runs fine when no polymorphism is considered but when i use Simp t=new Troy3(),i am not able to understand why i am getting 3 as the answer.. can anyone explain please??
as per me the sub constructor runs . and i can get why which cal method is being called? base or sub??? and how is the answer 3 ???

class Simp {
public int a;
public Simp() { a=3; }
public void cal() { a+=5; }
}
class Troy3 extends Simp {
public int a;
public Troy3() { a=8; }
public void cal() { this.a+=5; }
public static void main(String[] args) {
Simp t=new Troy3();
t.cal();
System.out.println("value is "+t.a);
}
}
 
mohammad shaid
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oopss.. sorry for posting such a simple code.. a is public in Simp class which can be accessed without the methods.. thats the reason i am getting 3 as the result.. .. thanks all..
 
Raza Mohd
Ranch Hand
Posts: 247
Java MyEclipse IDE MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
previously we were not accessing "a" with method name.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohammad shaid wrote:thanks all..

you are welcome. next time *use code tag* while posting code. so that it can be read easily
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Please UseCodeTags and QuoteYourSources

I didn't go through the code as it was not readable.

Hope this helps,
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!