• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

out put of class

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can any body explain the out put as iam getting answer 2 ;
* but answer is 1;
public class Poly
{
public static void main(String argc[])
{
A ref1=new C();
B ref2=(B)ref1;
System.out.println(ref2.g());
}
}
class A
{
private int f() {return 0; }
public int g() {return 3; }
}
class B exends A {
private int f() { return 1;}
public int g() { return f(); }
}
class C extends B {
public int f() { return 2; }
}
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by gouru:
can any body explain the out put as iam getting answer 2 ;
* but answer is 1;
public class Poly
{
public static void main(String argc[])
{
A ref1=new C();
B ref2=(B)ref1;
System.out.println(ref2.g());
}
}
class A
{
private int f() {return 0; }
public int g() {return 3; }
}
class B extends A {
private int f() { return 1;}
public int g() { return f(); }
}
class C extends B {
public int f() { return 2; }
}

I am using jdk1.2.2 and when this is ran, I get an output of 1. I thought the method that was chosen was based on the actual object? Could this result be because a B method made the call, it's method was chosen?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
the basic thing is that in method g() u r calling a private method f(). Remember that private methods are not overriden. thus class C method f() is not called.
if u change the B.f() method to public, protected, or default u will get the result that u expect.
if u have problems do tell me.
regds
Rahul.

[This message has been edited by rahul_mkar (edited June 21, 2000).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic